How to add a x-axis line to a figure? (matlab) - matlab

I want to add a x-axis line at 0 to a Matlab figure so that I can compare my data to see if it is positive or negative when saving the figures to a jpg. What is the best way to do this? I know you can use line() but it just seems cumbersome because you need to specify the x and the y ranges. Is there an easier way?

There exist an undocumented function graph2d.constantline:
plot(-2:5, (-2:5).^2-1)
%# vertical line
hx = graph2d.constantline(0, 'LineStyle',':', 'Color',[.7 .7 .7]);
changedependvar(hx,'x');
%# horizontal line
hy = graph2d.constantline(0, 'Color',[.7 .7 .7]);
changedependvar(hy,'y');
The nice thing is that it internally implements a listener for the axes limits (handles change like pan, zoom, etc..). So the lines would appear to extend to infinity.

You could get this x range directly after the figure has been created. It goes a little something like this:
x=-2:5;
y=x.^2-1;
figure()
plot(x,y);
xlim = get(gca,'xlim'); %Get x range
hold on
plot([xlim(1) xlim(2)],[0 0],'k')
Note that if you do any manual zooming out in the figure, the line might have to be redrawn to go over the entire new x range.

I don't believe there is a built-in way that is more convenient. I use hline() and vline() from FileExchange, which work like a charm:
http://www.mathworks.com/matlabcentral/fileexchange/1039

A vline and hline command like in GNU R would be great, but I could not find a shorter solution than
plot(1:10,sin(1:10));
line(xlim,[0 0],'Color','r')

Draw your data by plot() command or stem(). A figure window will open.
Then on the figure window, click on the [insert] command from the
menu bar, a drop-down menu will appear.
From this menu click on the [line] command, now the shape of the
cursor will change into a plus sign.
Now you can draw a line anywhere you want, either horizontal or
vertical or slanted.
You can change the properties of line by right clicking on the
line, a menu will appear from which you can choose your desires
properties.
If you want to have some ticks on the line then you can use add
text option, and place text where ever you want.
If you would like to have a code for your figure, click on [file]
menu and then click on [generatecode] option, a new text editor
window will open, you can save this code for further use. Good luck.

Since MATLAB R2018b there is yline for this purpose:
yline(0)
draws a horizontal line at y==0.

Related

Legend displayed wrongly, one entry is out of the box, one is inside

I just wanted to add a very simple legend to my plots. But every time I want to add a legend, it displays it as can be seen in the picture:
One entry has a very long line and the second entry is on the border of the box which makes it impossible to use this graphic for anything.
The code is pretty simple:
x=1:0.2:100;
y1=sin(x);
y2=sin(x+1);
x=x/100*6;
figure;
plot(x,y1);
hold on;
plot(x,y2)
legend('Referenzkanal 1','Referenzkanal 2')
What is the problem and how to fix it?
I'm using MATLAB R2017a on a Lenovo Thinkpad with Windows 10.

Remove Objects from Legend When You Have Also Used Fit, Matlab

I've plotted data points and fitted an exponential curve between them using 'fit' in Matlab. The problem is that with the fit-function I got the fitted line I wanted to plot, but also extra markers on top of my regular markers. I solved this problem by plotting the wanted markers on top of the unwanted so that they couldn't be seen. Now to the problem. When I want to show the legends those dots are also in there. How can I remove the markers from the legend without removing the fitted line since both of them are hidden inside the fit-function? Can I stop 'fit' from plotting the unwanted markers? So, I want to remove the blue dot called 'hoff' in the picture below.
You can leave out legend-entries by manually leaving out the handles of the lines, that you dont want to be in the legend. Try this:
%if you plot something, that you want showing up in the legend, save its handle:
h_line = plot(x,y)
%you dont want to show up this line? dont do anything, just plot it:
plot(myMarker)
%then set the legend-> you can add the text for your legend-entries with
%a cell-array containing the strings you want to show up:
legend([h_line another_line],{'Text1' 'Text2'})
with the example (see comments) I came to this solution:
close all
X=[1:10];
Y=X*0.5+0.1;
ft = fittype('poly2');
f = fit(X', Y',ft);
ha=plot(f)
hold on
hc=plot(X,Y)
hb=errorbar(X, Y, X*0.1, 'squarek','MarkerFaceColor','k','markersize',5)
hleg1 = legend([ha hc],{'hnh','ghg'});
-> this is just about splitting the plot-command. Hope that helps...
the result should look like this:

How can I order items in a Matlab legend via the figure editor?

I've created a histogram with multiple sets of data. The data sets are color imgages converted to grayscale and taken over a given time period (e.g. pic 1 # time=0, pic 2 # time=5min, etc.) which is why I need the legend entries to show up in a specific order. When I put the legend in, the entries are scattered around in no specific order and I can't figure out how to get the entries switched up the way I need them.
In 2017a and higher (using part of the answer by Peter M above)
Select "Edit Plot" with the standard arrow button in the toolbar. This will allow you to select plot lines.
Select the plot line you want to appear first in the legend.
Use Ctrl-X (or whatever on OS X,Linux) to "Cut" the Plot line.
Create a new figure (File -> New -> Figure).
Use Ctrl-V (or whatever on OS X, Linux) to "Paste" the Plot line in the new figure.
"Cut" the Plot line in the new figure.
"Paste" the Plot line in the original figure.
Repeat steps 2-6 for every plot line, in the order that you want
them to appear in the legend. Right click on the legend and
"Refresh"
If you are regenerating the plot often of course it is probably a good idea to make sure that the script puts them in the correct order. Luis Mendo provided an answer here, but his answer to a slightly different wording was a little more detailed: how to change the sequence of the legend.
Pre 2017a Only! It seems that 2017a breaks this behavior, so the following trick does not work in the latest versions.
To answer your specific question, here is a neat trick if you are just doing this once in awhile on a plot that doesn't have many lines, and only want to use the Figure Editor...
Select "Edit Plot" with the standard arrow button in the toolbar. This will allow you to select plot lines.
Select the plot line you want to appear first in the legend.
Use Ctrl-X (or whatever on OS X, Linux) to "Cut" the Plot line.
Use Ctrl-V (or whatever on OS X, Linux) to "Paste" the Plot line.
Repeat steps 2-4 for every plot line, in the order that you want them to appear in the legend.
Right click on the legend and "Refresh"
You can get a handle to each plotted object, and in the legend use the handles to control which string applies to which plotted object.
Example:
h1 = plot(1:5, 1:5, 'r');
hold on
h2 = plot(1:5, 2:6, 'b');
legend([h1 h2],'First red','Second blue')
The answer above also works for R2017a and higher...here is a little bit more general example:
x = 1:10;
y1 = x;
y2 = 2*x;
y3 = 3*x;
y4 = x.^2;
figure
plot(x, y1, x, y2, x, y3, x, y4);
lh = legend('y = x', 'y = 2*x', 'y = 3*x', 'y = x.^2');
legendEntries = get(gca,'legend')
plotHandles = get(gca,'children')
legendEntries = legendEntries.String;
newOrder = [3,4,1,2];
legend([plotHandles(newOrder)],legendEntries{newOrder})
flipud(h) or fliplr(h) to change complete order of the array up-down oder left-right
Through try and error I found this easy fix:
1) select the plot line that should be at position 1 (at the top)
2) Strg + X
3) Strg + V in the same plot figure
Repeat step 2 and 3 about 3 or 4 time. This will result in the plot beeing at the bottom of the legend. Now select the plot that should be at the 2nd position, again Step 2 and 3 a couple times. The previous plot moves one place up, the 2nd picked plot is now at the bottom.... continue with the rest of the plots the same way

Remove border around Matlab plot

Matlab is displaying a black border around a plot and I would like to remove it. I think i should be using something like:
set(Figure#,'PropertyName',PropertyValue);
But I'm not sure what PropertyName or PropertyValue should be used...
Edit:
I tried all of the suggestions including:
set(gca,'box','off');
set(gca,'xcolor','w','ycolor','w','xtick',[],'ytick',[]);
axis off;
The figure still has a black boarder and looks like this:
Edit 2:
This is a simplified package that reproduces the black box. Run the script called "runPlot". Here it is:
http://dl.dropbox.com/u/8058705/plotTest.zip
I can't figure out why the box is still visible. This might be due to the line in "plotTEC.m"
axis([-.65 .6 .25 1.32]) % hardwiring axis length since the coastline runs off of the plot
#Pursuit: If I use "plot browser" I get a recursive error....I am not familiar with the matlab plotting package but this seems strange. Does anyone else get this error? Again, thank you guys for your advise!
Does anyone have any other suggestions?
Thanks in advance!
You want to experiment with the properties of the axis. Some properties of interest.
xcolor %The color of the x-axis line and the x axis labels
ycolor %
box %'on', or 'off' indicating if one or both sides of a plot should have lines
xtick %Where to place the labels
ytick
For a completely bare plot, use:
figure
set(gca,'xcolor','w','ycolor','w','xtick',[],'ytick',[])
To set the figure background to white as well
set(gcf,'color','w')
Depending on your exact problem, you can try the 'box' property, to see how it affects your plots
set(gca,'box','on')
set(gca,'box','off')
If you want to turn off the actual plots lines but keep the plot labels then I am not aware of a simple solution. I think that I would need to remove the axes as described above, and then manually add labels using the text function.
Edit: As I just learned from this question, Plot Overlay MATLAB you can also try
axis off
axis on
Which I think is equivalent to
set(gca,'visible','off')
set(gca,'visible','on')
Edit 2:
If nothing else works, activate the "plot browser" in your figure. Use "view" --> "plot browser". From the plot browser panel, uncheck each object until you figure out which object is drawing the lines that you need to remove.
Then double click on the offending object to bring up the "property editor" panel, and mostly likely click "More properties" to view all possible properties of that object. From that view you can (hopefully) figure out what object is drawing the offending lines.
After you have figured out the object and property to edit, you can probably figure out where in the code that object is created, and set the property programmatically.
Try:
set(gca, 'Box', 'off');
Solution to remove 'gray' background in imagesc
I = imread('imgname.jpg');
[rows columns] = size(I);
posX = 100; posY = 100; %you can set any value for posX and posY - try to keep it on screen
f = figure (1);
imagesc(I);
set(gcf,'Position',[posX posY columns rows]);
set(gca,'units','pixels');
set(gca,'units','normalized','position',[0 0 1 1]);
axis off;
axis tight;
This should save the image with same size as that of the original, using imagesc.
Cheers!
set( gca , 'Visible' , 'off' );

In matlab, how can I zoom in on a plot in my script

I'd like to zoom in on a plot using a script. I'm only interested in horizontally constrained zooming. So I'd like to do something like
p = plot(myData);
z = zoom;
set(z, 'ZoomInToPoints' , [50 100]);
or
p = plot(myData);
myZoom([50, 100]);
So either of these functions would zoom into a plot like when you zoom in with the magnifying glass tool. I only specify two points because I only want to zoom horizontally.
Note, I've already tried to use xlim for this. While it works, it doesn't let me use the command text on my plots, which I need.
Calls to text will fix the text at a specific set of coordinates on the graph. Have you tried updating these after calling xlim?
EDIT: You can always adjust the text position:
x=1:.1:10;
y=sin(.1*x);
plot(x,y)
text(6,.8,'test') %#Sample figure
F=get(0,'children'); %#Figure handle
A=get(F,'Children'); %#Axes handle
T=findobj(A,'Type','text'); %# Text handle
oldxlim=xlim; %#grab the original x limits before zoom
oldpos=get(T,'Position'); %#get the old text position
set(A,'xlim',[5 15]); %#Adjust axes
newxlim=xlim;
newpos=[(oldpos(1)-oldxlim(1))*(diff(newxlim))...
/(diff(oldxlim))+newxlim(1) oldpos(2:end)];
%#interpolate to place the text at the same spot in the axes
set(T,'Position',newpos) %#Finally reset the text position
Not pretty, but it should work. If you have more than one annotation per axes or axes per figure, you can always throw the above code in a loop.
What is the problem with text and xlim? Is this not the type of behavior you want?
plot(1:100,randn(100,1))
text(80,1.5,'text')
set(gca,'XLim',[70 100]) % notice that text stays at same point in "data space" but moves in "axis space"
text(80,1,'text2'); % new text appears in axis space as well
If I'm misunderstanding and you want text to appear at a specific point in your axis space (not the data space that text uses) regardless of how zoomed in you are, you can create another set of axes for your text:
inset_h = axes('position',[0.5 0.5 0.2 0.2])
set(inset_h,'Color','none'); axis off
text(0,0,'text')