Plot over an image background in MATLAB

This is a short tutorial that documents how to make a MATLAB plot on top of an image background. This can be useful for a variety of things but when I first learned about it, I was a bit confused by how the axes seem to be flipped sometimes when you do this. In this tutorial I will give several examples that should illustrate how to plot on top of an image properly. I have used this technique for a few things, such as visualizing 1D and 2D classifier decision boundaries when I was preparing my thesis. I have also written a tutorial on how to do a 3D version of this in which an image is shown as a plane in a surface plot.

MATLAB plotPlotting on an image

Getting started

First, make a new .m file and load any image you want. In this example, I used a gray scale version of one of the images in my artwork gallery, specifically Gentoo Kung Fu, because it is easy to see which way is up in the image unless you think it is possible for a penguin to take on three guys in hand-to-hand combat while standing upside down. You should try it with your own image. Put the following into the .m file:

% replace with an image of your choice
img = imread('myimage.png');
% set the range of the axes
% The image will be stretched to this.
min_x = 0;
max_x = 8;
min_y = 0;
max_y = 6;
% make data to plot - just a line.
x = min_x:max_x;
y = (6/8)*x;

The above code defines the axes range that the image is stretched to and creates some (x, y) data to plot. The code examples that follow use the above data and variables.

The following code creates the plot itself. (0,0) starts at the bottom left as expected for a regular plot.


Desired plot to be shown over the image

Before getting started with some examples, first show the image in a MATLAB plot to take a look at how the image array (matrix) is actually stored in MATLAB:

xlabel('Raster Column');
ylabel('Raster Row');

The above code produces this:

Raster coordinates of the image

The coordinates given by (Raster Row, Raster Column) are the 0-based image coordinates. The image array is stored with (0, 0) as the top left corner of the image. In MATLAB's internal memory, (0, 0) corresponds to subscript (1, 1).

Some wrong examples

It is necessary to understand a bit about what MATLAB is doing when you tell it to show an image and add a plot on top of it. Sometimes the result is wrong and here are some examples with an explanation of why.

Example 1

The first example that shows an image as well as a MATLAB plot.

imagesc([min_x max_x], [min_y max_y], img);
hold on;

Here, the imagesc command is issued in imagesc(x,y,C) form, which will specify the range of axes labels that the image is displayed within (determined here by [min_x max_x] and [min_y max_y]). The hold on command is issued and then the (x, y) data are plotted. This is the result:

Example 1 - Y-axis reversed

You will notice that the plot and the Y-axis are now upside down but the image is displayed properly. The reason is when imagesc is used, MATLAB has reversed the Y-axis so that Y gets larger as you move down. This corresponds to making the Y-axis increase in the same direction as image raster coordiantes. When the plot is made, it is using the new, reversed Y-axis, thus explaining why it is flipped.

Example 2

We can tell MATLAB to flip the axis back to normal, as in the following code with set(gca,'ydir','normal'):

imagesc([min_x max_x], [min_y max_y], img);
hold on;
% set the y-axis back to normal.

This is the result:

Example 2 - Image reversed

Now the image is flipped. That's because when the Y-axis is set back to normal, it affects how MATLAB displays the figure. Y is small at the bottom and large at the top, so MATLAB will show the image upside down. It turns out the Y-axis direction specifies how MATLAB displays the image; the image raster row axes is always displayed in the same direction as the Y-axis. In other words, the image is displayed in such a way that the smallest raster row (which is 0) is at the smallest Y value visible on the axes, and the largest raster row is at the largest Y value visible on the axes.

Example 3

The hold on command should be issued after the image is displayed. Otherwise, the figure will retain the default set of axes when you display the image, without adjusting to the width and height of the image.

For example, try moving hold on to before the imagesc command in Example 2:

hold on; % hold on before the image causes incorrect results
imagesc([min_x max_x], [min_y max_y], img);
% set the y-axis back to normal.

The result will look like this:

Hold on should be issued after the image is displayed

The correct way

In order to resolve the problem from Example 2, the image can be flipped before displaying with the flipud command:

% Flip the image upside down before showing it
imagesc([min_x max_x], [min_y max_y], flipud(img));
% NOTE: if your image is RGB, you should use flipdim(img, 1) instead of flipud.
hold on;
% set the y-axis back to normal.

Here, the image is flipped first before displaying, so that the bottom of the image is now Y = 0. Then, the y-axis is set back to normal (where Y = 0 is at the bottom). This means that the bottom of the image (which is now Y = 0 due to flipud) is at the bottom of the plot. The result:

Correctly plotting on top of an image

This correctly shows the image and the plot. A few readers have pointed out that if your image is RGB, you can use the flipdim command instead of flipud:


One caveat: Although Example 1 and Example 2 from the previous section are called “incorrect”, they may actually give you the right result in some cases. The image in this tutorial depicts a scene that independently has a “right side up”. Image Row 0 must always be displayed at the top. There may be cases where the image you want to show is created within MATLAB and Image Row 0 might simply need to be associated with the smallest Y-coordinate shown on the axes. In that case, Example 1 or Example 2 might give you want you want. An example might be when you need to visualize classifier decision boundaries. In any case, the information in this tutorial should be enough to figure it out if needed.


chitra, 2011/05/04 03:50
sir, i am doing research wor in face recognition. in that i found the center point of an image(ie. nose part) and also center point of the forehead. now i want to draw a oval shape using this two points. wat function i use to draw a oval shape.
plz guide me
Peter Yu, 2011/05/04 19:07
Good question. As far as I know, there isn't a built-in function for drawing ovals / ellipses. There are some functions on the MATLAB File Exchange, for example:
Ricardo, 2011/06/14 17:17
Thanks a lot !!!!!!!!!!!!!

Just great, I was looking for a simple solution like this. You make my day
Amit, 2011/07/19 10:42
help imellipse
doc imellipse
Peter Yu, 2011/07/19 18:14
Yes, imellipse is a partial solution but I don't think it can do rotated ellipses.
tino, 2011/07/20 23:09
Thanks for your sharing, however, I have a question,

Is it possible to do this:

1. show an image a
2. plot over this image a
3. replace image a with an image b while keeping what I plotted in step 2.
Peter Yu, 2011/07/20 23:19
I don't know how to replace the image in an existing plot. I know you can get the handle to the image object when you make a call to, say, imagesc, e.g. h = imagesc(...). Maybe through the handle you can do something to the image. Is there a particular reason you can't just plot with image b in the first place?
Hussein, 2011/08/29 17:52
Hi Peter,
I have number of points coordinates measured in millimeters and would like plot them on the image. The coordinates are already stored in text points and they represent points appear in the image.
Peter Yu, 2011/08/30 21:37
All you should have to do is to set the limits of the image in millimeters and then plot the points directly.
koji, 2011/09/06 18:00
God bless you!!
GJKD, 2011/09/17 16:15
My solution to this same problem is to have a little function which flips x and y called OverlayPlot - but is otherwise identical to plot. It is annoying that plot can't understand to switch its origo.
Eric, 2011/09/23 08:29
Thanks a lot for sharing these detailed and very useful tips!
abhi, 2011/09/25 10:27
Hello sir,i liked the way u explained concept but i hav 1 problen as in my project i need to finding axis of symmetry.I hav found centroid using regionpropes function but not getting how to plot centroid.Plz help me to come out of this problem!
blo, 2011/10/06 09:12
Thx, works for me.
ikla, 2011/11/11 08:37
thanks for the great tutorial.

just to improve a little bit, though, you need to use flipdim(img,1) instead of flipud if you are using an RGB image.
Marcin, 2011/11/17 13:36
Thank you for the thorough and clear explanation! This is exactly what I was looking for. Also, I agree with ikla about RGB images.
Peter Yu, 2011/11/24 21:11
Thanks for pointing out the flipdim command. It turns out I've never tried plotting on an RGB image.
edwin, 2012/02/01 14:45
padmala ravi, 2012/03/15 05:31
sir i have a problem that after displaying the image if i plot something, the image disappears and the plot is displayed with a white background, i am using hold on after displaying image. please guide.
Peter Yu, 2012/03/20 22:46
Does my example work on it's own without any modifications? If so, check your code.
Kuffy, 2012/03/19 12:50
Thanks I got the explaination and I was able to produce the figure but I want to put a 2D line on a 3D plane/surf.Please
Peter Yu, 2012/03/20 22:48
How about using plot3? That lets you put a line or whatever else you want in 3D space.
warwick grace, 2012/05/20 03:41

It was generous of you to put your code and tutorial on the web. I wanted to overlay a simple plot onto a photo image. (Thought it would make an apt and upmarket image for a report I had to do).

I was able to do that and then do so with a bit of a twist; namely, locating the plot to wherever I wanted within the photo and then to have the background of the plot clear so that the photo still came through.

To be frank, I would never have been able to do it without your examples as a template.

Catherine, 2012/05/24 16:11
Peter, Awesome explanation-thank you very much. I'll be sure to keep an eye on your tutorials.Catherine
Donovan, 2012/07/17 08:54
Hi Peter, this was very useful for me. However, if I am using a semilog plot and I add the picture I lose the logarithmic scale... any ideas?

Peter Yu, 2012/07/17 22:29
Good question. I've never tried doing that before but perhaps this thread could give you some ideas:
Alex, 2012/10/04 13:30
In five minutes you resolve my one week problem, thanks a lot....
Mikhail Volkov, 2012/10/25 13:07
great article, solved my problem exactly!
yogesh, 2012/12/14 07:29
WOW Great Job.......
Emily, 2012/12/15 19:06
Thanks for the tutorial. Any idea how to use 'xdir', 'reverse' for the plot without affecting the image direction?

Peter Yu, 2012/12/23 23:31
Would pre-flipping the image work? I think there is a fliplr command to flip left right.
Mansoor, 2013/01/29 15:42
Is there any way to rotate an axes in MATLAB?
ruben, 2013/03/04 11:43
Hello everybody, i am trying to do this but in a 3d plot, but just ploting the image in the xy axis, how could i do it?
Peter Yu, 2013/03/04 14:31
Phil, 2013/03/13 07:34
nice! works very well
Charly, 2013/03/30 12:22
Excuse me,
If the pic matrix is 3-D and the order "flipud" must be 2-D matrix,
does it still work?
Tadeu, 2013/04/13 20:20
It doesn't work for me.

With this code:

img = imread('raia.png');

min_x = 0;
max_x = 80;
min_y = 0;
max_y = 60;

x = min_x:max_x;
y = (6/8)*x;


xlabel('Raster Column');
ylabel('Raster Row');

% Flip the image upside down before showing it
imagesc([min_x max_x], [min_y max_y], flipud(img));
hold on;

% set the y-axis back to normal.

Matlab says:
??? Error using ==> flipud at 19
X must be a 2-D matrix.

Error in ==> raia at 20
imagesc([min_x max_x], [min_y max_y], flipud(img));
Tadeu, 2013/04/13 20:23
Used flipdim(img,1); instead flipud
Hossein, 2013/05/06 16:22
Hello Peter, thanks very much for learning this program, it's very useful for me. i do that in the other way that doesn't work well because my method can't zoom on picture of background. i am very happy this time, for second time thank you.
your new friend from Iran,
Tomar, 2013/05/16 11:01
Hi I have a question related to this post. How do I keep the completed plot in the same Axes but change the image?

For example: I have number of images to point or plot on. and I do not want to do the same work again. I use impoint function for points and then plot between them. Now I move to next image in sequence. and the plot is lost. How do I retain the plot?
Peter Yu, 2013/08/09 21:38
Maybe get the handle of the plot object and change the image from there somehow? Unfortunately, I don't have a good answer to this.
Shaymae BOUCHKHI, 2013/06/01 19:13
first thank you for creating such a nice web site . However I woul like to ask you about an exercise that I am asked to give to my teacher as my last project of the year but I find some difficulty .
here is the exercise :
a/ find or take a picture of your self with a plain background such as green screen, using the JPEG image format.
b/Find a JPEG image of the place that you dream of and decide on the rectangle in the scene where your image should appear. save the width and height of the rectangle and row and column of its top left corner .
c/Re-size your image to be the width and height of the rectangle
d/Use the color masking technique to copy your image without the green screen into the selected rectangle of your dresm scene .
It would be great If you comment on code
thank you so much and I hope you can answer my questions because this is my last chance to get my marks !
Lilly, 2013/08/08 08:36
Hello Peter, thanks for yours beautyful explanation!! I have a queStion for you. I want to overlay an image in greyscale and a contour. Is it possible tO obtaine one figure with two different colorbar? Or a figure whit the colorbar associated to only the contour?
Peter Yu, 2013/08/09 21:36
It is possible to use a different colormap for the different objects if you convert the grayscale image to a true-colour representation and then use a specific colormap for the contour, sort of like the idea in my other tutorial:

You'd have to figure out how to show the colorbar in the figure.
hosein, 2013/09/16 01:42
Hi peter,I came across a problem.
I'd throw a picture on a page and rotate it.
I did this with the SURF Function
But when you rotate the image,
Image is missing.
ahmed, 2013/10/13 09:42
thanks a lot
que dieu te protege
الله يخليك
frenil, 2013/10/17 03:08

I had rotate my image at a particular degree but the problem is that it had got stretched like circular object become Elliptic,

xscale = 1;

yscale = 1;

rotation = 30;

oldimg = imread('myimage.png');

theta = rotation*pi/180;

As = [xscale 0; 0 yscale];

Ath = [cos(theta) -sin(theta);sin(theta) cos(theta)];

A = Ath*As;

T = eye(3,3);



newimg = imtransform(oldimg,tform);


Nick, 2013/10/27 08:04
This is truly a very useful information! Thank you very much, I think this could help a lot! Cute web-site here as well) I am wondering if you know whether the field distribution over a picture will work. I wand to visualise the environmental impact on a map. Any suggestions would be of a great help!)
Omar, 2014/02/13 08:30
How would you save the final image, after hold on?
Ahmed Zewain, 2014/03/13 11:49
Hello i have a simple problem. Im working with data from GRACE sattilites. the data is stored as a matrix, and i use imshow(Data) to show the distribution of data around the world. the problem is i need coastlines on top of the data so i can clearly see the continents, and this does not work:

load coast

hold on
hold off
Peter Yu, 2014/03/21 21:34
I guess the image is not scaled to the coastline data's bounds and so they don't show up.
ap, 2014/03/18 10:06
Great website! So if I understand correctly imagesc scales the image to the dim of plot given such that corresponce between image and plot will be shown ? Thanks!
Peter Yu, 2014/03/21 21:33
imagesc just scales the gray values of the image to your display range. I use it as a habit because I used to work with images of different data types (0 to 1 or 0 to 255, etc) and I just wanted to visualize them properly.
wale Abiye, 2014/08/08 08:40
Dear Sir, Thank you for the great tutorial. please i need to make a contour plot on an areal map. how do i go about it please. thank you.
Abdullah Khlaif, 2014/08/22 19:17
how can i but an image in a 3D plot ??
christi, 2014/08/31 22:14
hi I would like to know how to represent an image in graph
Amean, 2014/09/15 09:48
hello peter

I have disparity map of the plant leave, how can I draw plane that include the majority of these point i have no idea how to start, can you help me please
Rajab, 2014/09/19 05:40
Hi Peter

Thanks for your great tutorial, do you have any idea how to set up the image axes to be (log log). I need to plot some points on image that shows log-log graph.

Mahmoud Alhalak, 2014/11/17 05:37
Hello Peter, thanks very much for learning this program, it's very useful for me.

I'm just would to ask if we can take a data from the image (X-components,Y-components of some points on the image), where my image is curve.
Dionysia, 2014/11/25 09:39
Hello Peter,
your tutorial is great!!!
Thank you very much for sharing it!
patel, 2015/01/30 09:22
Hello peter,
what to do if same line are taken or draw on the sequence of frames of video??
prajaya, 2015/04/19 12:55
Hi Peter,

How can I plot data over a map and set the scale of graph and map the same? Also I want to be able to change the origin of graph so that I can place it to right location of map. Suggestions and hints will be gladly appreciate.

thank you
Olalekan, 2015/05/12 09:47
hi, i worked on an iris recognition project using UBIRIS database with MATLAB progeramming. the project was succesful. Now a friend of mine is given the same project with CASIA database and the eyes have occlusions (Eyelid and Eyelashes). please how do i go about removing this occlusions.i was able to segment iris region but i love to remove the occlusions before Normalizing. please kindly assist.
Chris, 2015/07/18 06:31
Hello Peter,

I want to say that I found you tutorial extremelly helpfull and a very good start for my task.

My problem is the following. I have my image streched correctly along the axis but when I try to overlay a 2D surface(with trasnparency) plot with the 3rd dimension as colour the result is that I see the picture behind the graph as I should but the plot seems to be in one colour only.

I'll send you my code.

I hope you can give me an answer or at least sth to look.

Thank you in advance.

Chris, 2015/07/18 06:34

min_x = 1;

max_x = 4;

min_y = 1;

max_y = 4;

C = imread('C:\Users\user\Desktop\greece.jpg');

imagesc([min_x max_x], [min_y max_y], flipdim(C,1));

hold on;

set(gca,'ydir' , 'normal');

%set(gca,'ydir' , 'normal');

[X,Y] = meshgrid(-8:.5:8);

R = sqrt(X.^2 + Y.^2) + eps;

Z = sin(R)./R;

pcolor(X,Y,Z); shading interp;

shankar, 2016/01/14 00:39
This helped a lot!! Thanks! :)
Santi Singh, 2016/05/02 13:35
Plz suggest me for the code...... I am trying to write code to find out locations of pcb drilling holes. My conditions are 1. pcb image should not be stretched 2. coordinate should be world coordinate for easy note of coordinates 3. image should be shown with grid to find the coodinates i.e. x and y values so that these x,y values can be entered into CNC G-code for drilling purpose........ Thanks
Fahime, 2016/09/02 09:20
How can i save points of centroid after plotting on original image as another one?


hold on;

for x = 1: numel(stat)


Younis, 2016/09/06 18:06
My project used a remotely sensed image for automatic classification of urban materials (as a first stage of my work) to identify objects of different group of classes or individual classes: e.g. buildings, parking lots, roads, soil, grass, and water basins.

I would really appreciate if you could help me with that please in terms of suggested Matlab code.

Thanks in advance and kind regards,
John R, 2016/12/22 12:32
Thank you for this--very good.
Reversing the order of the coordinates min_y and max_y also flips the image up/down:
image([min_x max_x], [max_y min_y], img);

Plotting at this point will be upside down; if you type:
you can note that that the y axis property YDir is 'reverse'.

Thus the need for:
Joshua S., 2017/03/10 06:35
This is fantastic, thank you Peter.
noura, 2017/10/27 18:08
thank you so much. can you help me,please ..i am trying to draw butterfly or any mathematics shapes according to their function above white image in matlab.

how can you advice me?

thanks again
flower, 2017/11/07 03:06
Wonderful and Helpful!

Thank you.
JC, 2017/11/10 13:25
Wonderful tutorial. Thank you so much.
george, 2018/08/03 18:41
thank you for your tutorial, i need to put a logarithmic scale in the Xaxis in the image, plz help me...
warwick, 2018/11/16 04:37
Thank you.

I wanted to overlay weather station sites on a user-friendly map from the tourist office. Simply set min and max lat and longs) which entailed a bit of inspection on Google Earth) and and Hey presto - geo-located weather towers on the tourist map.
didi, 2019/05/17 03:12
Many thanks! helped a lot! :)
kaiming, 2019/12/15 22:02
how to display the background image without stretching ( aspect ratio of x and y)?
Mathphys, 2020/05/18 10:32
Nice! Mv problème IS to save under octave thé image with the overlapped plot under a JPEG file. How to proceed? Thanks
I would love to hear your feedback. Enter your comment below [ Terms of Use ]:

About Peter Yu I am a research and development professional with expertise in the areas of image processing, remote sensing and computer vision. I received BASc and MASc degrees in Systems Design Engineering at the University of Waterloo. My working experience covers industries ranging from district energy to medical imaging to cinematic visual effects. I like to dabble in 3D artwork, I enjoy cycling recreationally and I am interested in sustainable technology. More about me...

Feel free to contact me with any questions about this site at [user]@[host] where [user]=web and [host]

Copyright © 1997 - 2021 Peter Yu