# 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.  ## 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

% 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.

`plot(x,y,'b-*','linewidth',1.5);` 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:

```figure;
imagesc(img);
xlabel('Raster Column');
ylabel('Raster Row');
colormap(gray);```

The above code produces this: 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;
plot(x,y,'b-*','linewidth',1.5);```

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: 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;
plot(x,y,'b-*','linewidth',1.5);

% set the y-axis back to normal.
set(gca,'ydir','normal'); ```

This is the result: 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);
plot(x,y,'b-*','linewidth',1.5);

% set the y-axis back to normal.
set(gca,'ydir','normal'); ```

The result will look like this: ## 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;
plot(x,y,'b-*','linewidth',1.5);

% set the y-axis back to normal.
set(gca,'ydir','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: 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`:

`flipdim(img,1);`

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.

## Discussion

, 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
, 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:

http://www.mathworks.com/matlabcentral/fileexchange/289-ellipse-m
, 2011/06/14 17:17
Thanks a lot !!!!!!!!!!!!!

Just great, I was looking for a simple solution like this. You make my day
, 2011/07/19 10:42
Matlab>
help imellipse
doc imellipse
, 2011/07/19 18:14
Yes, imellipse is a partial solution but I don't think it can do rotated ellipses.
, 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.
, 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?
, 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.
, 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.
, 2011/09/06 18:00
God bless you!!
, 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.
, 2011/09/23 08:29
Thanks a lot for sharing these detailed and very useful tips!
Eric
, 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!
, 2011/10/06 09:12
Thx, works for me.
:)
, 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.
, 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.
, 2011/11/24 21:11
Thanks for pointing out the flipdim command. It turns out I've never tried plotting on an RGB image.
, 2012/02/01 14:45
Nice!
, 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.
, 2012/03/20 22:46
Does my example work on it's own without any modifications? If so, check your code.
, 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
, 2012/03/20 22:48
How about using plot3? That lets you put a line or whatever else you want in 3D space.
, 2012/05/20 03:41
Peter

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.

thanks
WG
, 2012/05/24 16:11
Peter, Awesome explanation-thank you very much. I'll be sure to keep an eye on your tutorials.Catherine
, 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?

Thanks!
, 2012/07/17 22:29
Good question. I've never tried doing that before but perhaps this thread could give you some ideas:

, 2012/10/04 13:30
In five minutes you resolve my one week problem, thanks a lot....
, 2012/10/25 13:07
great article, solved my problem exactly!
, 2012/12/14 07:29
WOW Great Job.......
, 2012/12/15 19:06
Thanks for the tutorial. Any idea how to use 'xdir', 'reverse' for the plot without affecting the image direction?

Thanks!
, 2012/12/23 23:31
Would pre-flipping the image work? I think there is a fliplr command to flip left right.
, 2013/01/29 15:42
Hello,
Is there any way to rotate an axes in MATLAB?
, 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?
, 2013/03/04 14:31
http://www.peteryu.ca/tutorials/matlab/image_in_3d_surface_plot_with_multiple_colormaps
, 2013/03/13 07:34
nice! works very well
, 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?
, 2013/04/13 20:20
It doesn't work for me.

With this code:

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

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

plot(x,y,'b-*','linewidth',1.5);

figure;
imagesc(img);
xlabel('Raster Column');
ylabel('Raster Row');
colormap(gray);

% Flip the image upside down before showing it
imagesc([min_x max_x], [min_y max_y], flipud(img));
hold on;
plot(x,y,'b-*','linewidth',1.5);

% set the y-axis back to normal.
set(gca,'ydir','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));
, 2013/04/13 20:23
, 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.
Hossein.
, 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?
, 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.
, 2013/06/01 19:13
Hi;
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 !
, 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?
, 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:

http://www.peteryu.ca/tutorials/matlab/image_in_3d_surface_plot_with_multiple_colormaps

You'd have to figure out how to show the colorbar in the figure.
, 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.
, 2013/10/13 09:42
thanks a lot
que dieu te protege
الله يخليك
, 2013/10/17 03:08
hey,

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;

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);

T(1:2,1:2)=A;

tform=maketform('affine',T);

newimg = imtransform(oldimg,tform);

size(newimg)

figure,imshow(newimg);
, 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!)
, 2014/02/13 08:30
Hi;
How would you save the final image, after hold on?
Thanks,
, 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:

imshow(th_world(:,:,1));

hold on
worldmap('World');
plotm(long,lat);
hold off
, 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.
, 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!
, 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.
, 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.
, 2014/08/22 19:17
Hi;
how can i but an image in a 3D plot ??
, 2014/08/31 22:14
hi I would like to know how to represent an image in graph
, 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
, 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.

Regards
, 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.
, 2014/11/25 09:39
Hello Peter,
Thank you very much for sharing it!
, 2015/01/30 09:22
Hello peter,
what to do if same line are taken or draw on the sequence of frames of video??
, 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
, 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.
, 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.

Chris
, 2015/07/18 06:34
figure;

min_x = 1;

max_x = 4;

min_y = 1;

max_y = 4;

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;

alpha(0.4);
, 2016/01/14 00:39
This helped a lot!! Thanks! :)
, 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
, 2016/09/02 09:20
How can i save points of centroid after plotting on original image as another one?

imshow(s)

hold on;

for x = 1: numel(stat)

plot(stat(x).Centroid(1),stat(x).Centroid(2),'r*');

end
, 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,
Younis
, 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);

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

Thus the need for:
set(gca,'ydir','normal');
, 2017/03/10 06:35
This is fantastic, thank you Peter.
, 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.

thanks again
, 2017/11/07 03:06

Thank you.
, 2017/11/10 13:25
Wonderful tutorial. Thank you so much.
, 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...
, 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.
, 2019/05/17 03:12
Many thanks! helped a lot! :)
, 2019/12/15 22:02
how to display the background image without stretching ( aspect ratio of x and y)?
, 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 