matlab : suppress legend entry without removing from Plot Browser - matlab

One can suppress a legend entry for a line object h by executing h.HandleVisibility='off' or h.Annotation.LegendInformation.IconDisplayStyle='off'. However, both actions also prevent the curve from appearing in Matlab's Plot Browser user interface, and thus display of the curve cannot be interactively toggled.
Is there any way to suppress a legend entry for a given curve without also removing the ability to toggle display of that curve in the Plot Browser user interface?

You can also turn off handle visibility. This is way easier than having to set every plot as h1 = ...
Example:
x1 = randperm(10);
y = randperm(10);
x2 = randperm(10);
plot(x1, y, '-', 'Color', 'black', 'HandleVisibility', 'off')
hold on
plot(x2, y, '-', 'Color', 'green', 'DisplayName', 'Put This In Legend')
lgd = legend;
set(lgd, 'Location', 'best')

MATLAB's legend function accepts an optional argument listing the handles to include in the legend:
figure, hold on
h1 = plot(1,1,'ro');
h2 = plot(1,2,'gx');
h3 = plot(2,1,'m*');
legend([h1,h3]); % don't make a legend for h2.

Related

Accumulating plot of data and fit in Matlab

I have a Matlab script that imports data from a file and creates an exponential fit. I want the script to plot the data points and the fit using the same colour. The legend should be the name of the data file. When I run this same script again for another input file I want the new data and fit to be displayed in the same plot window name of the new data file added to the legend.
What I have so far is this;
expfit = fit(x,y,'exp1')
figure(1)
hold all
plot(x,y,'*','DisplayName','fileName)
legend('Interpreter','none')
legend show
using
plot(expfit,x,y,'DisplayName','fileName')
does not work
How can I add the fitted line to each data using the same colour as the data and
adding the filenames to the legend ?
You're close...
An easy way is to get the colours up front
c = parula(7); % default colour map with 7 colours
figure(1); clf;
hold on
% filename is a variable e.g. filename = 'blah.csv'; from where the data was loaded
plot( x, y, '*', 'DisplayName', filename, 'color', c(1,:) );
plot( expfit, x, y, '-', 'HandleVisibility', 'off', 'color', c(1,:) );
legend('show');
Note by setting HandleVisibility off the fit will not show up in the legend. This is personal preference, I only like one entry for the data and the fit, you could instead use the DisplayName on the 2nd plot too.
Both plots use the same colour using the color input. I've used the first row of the colour map for both, if you plotted some other data you could use the 2nd row etc.
The alternative is to let MATLAB determine the colour automatically and just copy the colour over for the 2nd plot, you need to create a variable (p) of the first plot to get the colour
p = plot( x, y, '*', 'DisplayName', filename );
plot( expfit, x, y, '-', 'HandleVisibility', 'off', 'color', p.Color );
The other code would be the same.

How to add an independent text in MATLAB plot legend

I need an additional text in the legend that is not related with graphical data together with the legend captions.
Something like this (it was made in OriginLab):
Following to this link Add custom legend without any relation to the graph
I can add some text using plot(NaN,NaN,'display','add info here2', 'linestyle', 'none'). But there is an indent in this text:
How to avoid this indent? And is there a more elegant method to add the text that is not associated with the legend together with the legend captions?
The legend function will return as its second output argument handles for all of the components that make up the symbols and text in the legend. You can therefore plot "dummy" lines as placeholders in the legend, reorder the handles when creating the legend to put the text where you want it, and modify the legend objects accordingly. Here's an example:
x = linspace(0, 2*pi, 100);
hl = plot(x, [sin(x); cos(x); tan(x); nan(size(x))].'); % Add a line of NaNs
axis([0 2*pi -4 4]);
[~, objH] = legend(hl([1 2 4 3]), 'sin', 'cos', 'junk', 'tan'); % Reorder handles
set(findobj(objH, 'Tag', 'junk'), 'Vis', 'off'); % Make "junk" lines invisible
pos = get(objH(3), 'Pos'); % Get text box position
set(objH(3), 'Pos', [0.1 pos(2:3)], 'String', 'also...'); % Stretch box and change text
You can use annotations. It's not perfect, but with few adjustments you'll get what you want. Here's an example:
% somthing to plot:
x = [0:0.1:5; 5:0.1:10].';
y = sin(x);
% plot the real data:
plot(x,y);
hold on
% make some space in the legend:
Spacing_lines = 3;
h = plot(nan(size(x,1),Spacing_lines));
hold off
set(h,{'Color'},{'w'}); % clear the dummy lines
% place the legend:
hl = legend([{'lable1','lable2'} repmat({''},1,Spacing_lines)]);
% add your text:
annotation('textbox',hl.Position,'String',{'Some info';'in 2 lines'},...
'VerticalAlignment','Bottom','Edgecolor','none');
And from this you get:
You can just add any text to any point of plot in this way:
txt1 = 'some information';
text(x1,y1,txt1)
where x1, y1 - coordinates.
By the way function text function has a lot of different properties (colors, font size, alignment etc.).
I think the easiest way is to just create some dummy function, plot it but set the color="none" - that way it will only show up in the legend (if that is where you wanted it).

Add custom legend without any relation to the graph

I wish to insert a legend that is not related to the graph whatsoever:
figure;
hold on;
plot(0,0,'or');
plot(0,0,'ob');
plot(0,0,'ok');
leg = legend('red','blue','black');
Now I wish to add it to another figure:
figure;
t=linspace(0,10,100);
plot(t,sin(t));
%% ADD THE LEGEND OF PLOT ABOVE
This is how I have solved this problem in the past:
figure
t=linspace(0,10,100);
plot(t,sin(t));
hold on;
h = zeros(3, 1);
h(1) = plot(NaN,NaN,'or');
h(2) = plot(NaN,NaN,'ob');
h(3) = plot(NaN,NaN,'ok');
legend(h, 'red','blue','black');
This will plot the additional points, but because the coordinates are at NaN they will not be visible on the plot itself:
EDIT 26/10/2016: My original answer results in greyed out legend entries in 2016b. The updated code above works, but the answer below is only relevant pre-2016b:
figure
t=linspace(0,10,100);
plot(t,sin(t));
hold on;
h = zeros(3, 1);
h(1) = plot(0,0,'or', 'visible', 'off');
h(2) = plot(0,0,'ob', 'visible', 'off');
h(3) = plot(0,0,'ok', 'visible', 'off');
legend(h, 'red','blue','black');
This will plot the additional points, but they will not be visible on the plot itself.
You can also use copyobj to copy graphics elements from one figure to another if you have a lot of elements, then use set(x, 'visible', 'off') to hide them before showing the legend, but it depends on what your final application is.
Your question is a little unclear. However, the first thing I thought of when reading it was the text function in Matlab.
You can use the text function to add text to a Matlab figure. It's use is
>> text(x, y, str);
where x and y are the coordinates in the figure where you want to add the text str. You can use the Color option of text for colours and TeX to draw lines or even _. I've gotten very creative with plots using text.
Here's a quick and dirty example of emulating a legend with text
x = 0:pi/20:2*pi;
y = sin(x);
plot(x,y)
axis tight
legend('sin(x)');
text(5.7, 0.75, 'sin(x)');
text(5.1, 0.78, '_____', 'Color', 'blue');
which produces
For this specific case you could use the specific command (noted by #Hoki in the comments).
ht = text(5, 0.5, {'{\color{red} o } Red', '{\color{blue} o } Blue', '{\color{black} o } Black'}, 'EdgeColor', 'k');
to produce
by retrieving the handle to the text object it becomes trivial to copy it to a new figure, copyobj(ht, newfig). [1]

How can I show only the legend in MATLAB

I want to show only the legend for a group of data in MATLAB.
The reason I want to do this is that I want to export the legend to .eps, but I only want the legend, not the plots.
Is there a way to turn off the plots and remove them from the figure, but still show just the legend centered?
This seems to do the trick:
plot(0,0,'k',0,0,'.r') %make dummy plot with the right linestyle
axis([10,11,10,11]) %move dummy points out of view
legend('black line','red dot')
axis off %hide axis
There is probably a lot of whitespace around the legend. You could try to resize the legend by hand, or save the plot and use some other program to set the bounding box of the eps.
The chosen solution by Marcin doesn't work anymore for R2016b because MATLAB's legend will automatically gray out invisible plots like this:
Neither turning off the automatic update of the legend nor changing the TextColor property afterwards fixes this. To see that, try Marcin's modified example:
clear all; close all;
figHandle = figure;
p1 = plot([1:10], [1:10], '+-');
hold on;
p2 = plot([1:10], [1:10]+2, 'o--');
legHandle = legend('text1', 'text2');
%turn off auto update
set(figHandle,'defaultLegendAutoUpdate','off');
set(p1, 'visible', 'off');
set(p2, 'visible', 'off');
set(gca, 'visible', 'off');
%set legend text color to black
legHandle.TextColor = [0 0 0];
The result remains the same. (To avoid throwing my laptop through the window) and fix this without zooming, which might leave fragments of the plot in the way, I wrote a function that fixes the legend and saves it to a file (with frame):
function saveLegendToImage(figHandle, legHandle, ...
fileName, fileType)
%make all contents in figure invisible
allLineHandles = findall(figHandle, 'type', 'line');
for i = 1:length(allLineHandles)
allLineHandles(i).XData = NaN; %ignore warnings
end
%make axes invisible
axis off
%move legend to lower left corner of figure window
legHandle.Units = 'pixels';
boxLineWidth = legHandle.LineWidth;
%save isn't accurate and would swallow part of the box without factors
legHandle.Position = [6 * boxLineWidth, 6 * boxLineWidth, ...
legHandle.Position(3), legHandle.Position(4)];
legLocPixels = legHandle.Position;
%make figure window fit legend
figHandle.Units = 'pixels';
figHandle.InnerPosition = [1, 1, legLocPixels(3) + 12 * boxLineWidth, ...
legLocPixels(4) + 12 * boxLineWidth];
%save legend
saveas(figHandle, [fileName, '.', fileType], fileType);
end
Tips for use:
fileType is a string that specifies a valid argument for saveas(), such as 'tif'.
Use it after you have plotted everything you want to appear in your legend, but without extra stuff. I'm not sure if all potential elements of a plot contain an XData member that isn't empty.
Add other types of displayed things that you want deleted, but are not of type line if there are any.
The resulting image will contain the legend, its box, and a little bit of space around it the legend is smaller than the minimum width (see Minimum Width of Figures in MATLAB under Windows). However, this is usually not the case.
Here is a complete example using the function from above:
clear all; close all;
fig = figure;
p1 = plot([1:10], [1:10], '+-');
hold on;
p2 = plot([1:10], [1:10]+2, 'o--');
legendHandle = legend('myPrettyGraph', 'evenMoreGraphs');
saveLegendToImage(fig, legendHandle, 'testImage', 'tif');
I think that you need to "hide" the elements you don't want in your plot, leaving out only the legend. For example,
clear all; close all;
figure;
p1 = plot([1:10], [1:10], '+-');
hold on;
p2 = plot([1:10], [1:10]+2, 'o--');
legend('text1', 'text2');
set(p1, 'visible', 'off');
set(p2, 'visible', 'off');
set(gca, 'visible', 'off');

In MATLAB, how does one clear the last thing plotted to a figure?

In MATLAB, I plot many different vectors to a figure. Now, what I would like to do is simply undo the last vector that I plotted to that figure, without clearing everything else. How can this be accomplished? Can it be accomplished?
Thanks
Edit:
figure(1); clf(1);
N = 100;
x = randn(1,N);
y = randn(1,N);
z = sin(1:N);
plot(x); hold on;
plot(y,'r');
plot(z,'k');
Now here, I would like to remove the plot z, which was the last plot I made.
If you know before plotting that you want to remove it again later, you can save the handle returned by plot and delete it afterwards.
figure;
h1 = plot([0 1 2], [3 4 5]);
delete(h1);
Try
items = get(gca, 'Children');
delete(items(end));
(or maybe delete(items(1)))
The answer that #groovingandi gives is the best way to generally do it. You can also use FINDALL to find the handle based on the properties of the object:
h = findall(gca, 'type', 'line', 'color', 'k');
delete(h);
This searches the current axes for all line objects (plot produces line objects) that are colored black.
To do this on, say, figure 9, you need to find the axes for figure 9. Figure handles are simply the figure number, so:
ax = findall(9, 'axes');
h = findall(ax, 'type', 'line', 'color', 'k');
delete(h);