Remove Objects from Legend When You Have Also Used Fit, Matlab - 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:

Related

How to prevent the legend from updating in R2017a and newer?

Since MATLAB R2017a, figure legends update automatically when adding a plot to axes. Previously, one could do this:
data = randn(100,4);
plot(data)
legend('line1','line2','line3','line4')
hold on
plot([1,100],[0,0],'k-')
to plot four data lines with a legend, and then add a black line for y=0. However, since R2017a, this leads to the black line being added to the legend, with the name "data1".
How do I prevent this line from being added to the legend, so that the code behaves like it did in older versions of MATLAB?
The only solution I have found so far on Stack Overflow is to remove the legend item after it has been added. The syntax is not pretty:
h = plot([1,100],[0,0],'k-'); % keep a handle to the added line
set(get(get(h,'Annotation'),'LegendInformation'),'IconDisplayStyle','off');
The release notes for MATLAB R2017a mention this change, and provide 4 different ways of handling the situation. These two methods are easiest to put into existing code:
1: Turn off auto updating for the legend before adding the black line. This can be done at creation time:
legend({'line1','line2','line3','line4'}, 'AutoUpdate','off')
or after:
h = findobj(gcf,'type','legend');
set(h, 'AutoUpdate','off')
You can also change the default for all future legends:
set(groot,'defaultLegendAutoUpdate','off')
2: Turn off handle visibility for the black line that you don't want added to the legend:
plot([1,100],[0,0],'k-', 'HandleVisibility','off')
The IconDisplayStyle method is also shown here. However, they use the dot notation, which makes the syntax is a bit prettier:
h = plot([1,100],[0,0],'k-'); % keep a handle to the added line
h.Annotation.LegendInformation.IconDisplayStyle = 'off';

How to get rid of blue line in regression plot in matlab?

I have a regression plot with a blue (lsline) which I want to eliminate it but I don't know how.
plotregression(y.testTargets, y.outputs)
If you want to remove just the blue line you can use findall to retrieve the handle to the line object and then delete it. Also based on #rayreng's feedback, I made it so that the line is automatically removed from the legend as well.
r = plotregression(rand(5,1), rand(5,1));
%// Make the legend dynamic before removing the line
legend('-DynamicLegend', 'Location', get(legend, 'Location'));
%// Remove the blue line (with the "Fit" label)
delete(findall(r, 'DisplayName', 'Fit'));

how to change the sequence of the legend

I want to change the sequence of the legend.
See the figure. I want the sequence to be: green and data2, blue and data3, black and data4, red and data1.
Could anyone give a demo?
Change the order in which the plots are added to the figure, and then call legend normally. That should do it.
You can also do it as follows. First get handles to the individual plots:
h1 = plot(1:5);
hold on
h2 = plot(11:15, 'r');
Then call legend specifying the order:
legend([h1 h2],'plot1','plot2')
or
legend([h2 h1],'plot2','plot1')
In case, you have already made the plots or if you added some plot at the end, which want to reorder to somewhere in middle, you can try this way:
1) Go to show Plot Tools and Dock Figure.
2) Delete the data (which you want to move to bottom). Then undo delete.
3) Refresh legend.

How to change the axes labels on a boxplot

When using the boxplot command from Statistics toolbox, the axes properties change in a strange way. For example, one gets
XTick = []
XTickLabel =
XTickLabelMode = manual
XTickMode = manual
What is happening to the axes and how one can rename the labels, and/or drop some of the ticks?
Try calling boxplot using the optional labels parameter.
Edit - further information about what boxplot actually does.
boxplot does some complicated stuff - type edit boxplot to take a look through the code, and you'll see it's a very long and intricate function. Basically it makes a blank axis with no axis labels, which is why you're seeing empty values for XTick etc. Then it makes the boxplot elements out of individual lines, and it simulates fake axis labels by adding text elements. You can find them and modify them directly by plotting into a figure f, then getting the Children of f, then iterating through to get their Children. Eventually you'll find text elements with the label names.
Try this:
xtix = {'A','B','C'}; % Your labels
xtixloc = [1 2 3]; % Your label locations
set(gca,'XTickMode','auto','XTickLabel',xtix,'XTick',xtixloc);
For some reasons resetting XTickMode to auto seemed to be key.
Thank you, Sam Roberts, that was helpful.
I wrote the following to remove group labels based on this advice. However, it removes ALL the labels, including axis and data tips. There doesn't seem to be a way to remove a label on an axis but leave it on a data tip.
m = get(get(get(figH,'Children'),'Children'),'Children');
for ii = 1:numel(m)
if(strcmp(get(m(ii),'Type'),'text'))
set(m(ii),'String', '');
end
end
The variable figH is the handle to your figure. You can also try gcf if the boxplot is the active figure handle.

How to add a x-axis line to a figure? (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.