Can we add legend for function "text" to matlab? - matlab

I want to add legend for my plot. Because I want to use the marker plot 'heartsuit', I use the 'text' function. If I add legend function in my code, it can't work. The command window say that 'Warning: Plot empty.' So, can we add legend to 'text' function? I have searched in many source, and I cannot find it.
clear all;
clc;
m = '\heartsuit';
x = 0:pi/5:2*pi;
y = sin(x);
text(x,y,m,'fontname','Arial','color','red','FontSize',18,'HorizontalAlignment','center','VerticalAlignment','middle');
grid on;
xlim([min(x) max(x)])
ylim([min(y) max(y)])
legend('Solusi Numerik');

Here's a hack. Plot a fake NaN point, create a legend for it, hide its legend line, and add the heart-suit in the string with appropriate space at an appropriate position. Adjust the color of heart-suit and/or string if needed.
hold on;
LgdStr = 'Solusi Numerik'; %Your legend string
hNaN = plot(NaN,NaN); %Plotting nothing
[~, icons] = legend(hNaN, LgdStr);%Creating a legend to get required space for string
icons(2).Visible = 'off'; %Hiding the fake legend line
icons(1).Position(1) = 0.125; %Adjusting the starting position of text
icons(1).String = ['\color{red}', m, ' \color{black}',LgdStr];
%Last line includes red-colored heart-suit at reasonable space from black-colored text
Result:

Related

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

Extract MATLAB legend string from existing plot

I've been trying to get some of the data back out of a plot that's been previously created, but I've been struggling with the legend. I'm using MATLAB 2014b.
If I previously set my plot up using:
h.fig = figure();
h.ax = axes(); hold all;
h.line1 = plot(0:0.01:2*pi(), sin(0:0.01:2*pi()));
h.line2 = plot(0:0.01:2*pi(), cos(0:0.01:2*pi()));
h.xlab = xlabel('X');
h.ylab = ylabel('Y');
h.leg = legend('sin(x)', 'cos(x)');
Then without having h available I can still retrieve the x and y axis labels as strings:
xlab = get(get(gca, 'xlabel'), 'string');
ylab = get(get(gca, 'ylabel'), 'string');
However, I don't seem to be able to extract the text from a legend in a similar way. I notice that:
fig_children = get(gcf, 'children');
Shows me both the axes and legend as the children of the figure, but I don't seem to be able to access them in the same way I might with the axes:
ax = get(gca);
I'm probably mis-understanding something obvious about the way that it works, but I can't find a way to get the string out of a legend that's been previously made?
The legend text is associated to the line, rather than to a legend object, so:
ax_children = get(gca, 'children');
Outputs a line array of the lines I was plotting:
ax_children =
2x1 Line array:
Line (cos(x))
Line (sin(x))
And then:
leg_strings = get(ax_children, 'displayname');
Outputs a cell array:
leg_strings =
'cos(x)'
'sin(x)'
Which is what I was looking for.
To get the legend handle (assuming only one exists in the figure, otherwise you'll have to sort them out) you can use the following:
findobj(gcf,'type','Legend')
ans =
Legend (sin(x), cos(x)) with properties:
String: {'sin(x)' 'cos(x)'}
Location: 'northeast'
Orientation: 'vertical'
FontSize: 9
Position: [0.7226 0.8325 0.1589 0.0619]
Units: 'normalized'
Then the legend entries are available as cell array.
In short:
leg_strings = get(findobj(gcf,'type','Legend'),'String');

how to decrease the legend width in matlab

I am using the matlab to plot some project figures, see the blow figure. Now I am trying to cut the legend width so that the line won't look so wide. I tried these command as suggest by Benoit_11:
[~,icons,~,~] = legend(leg,'location','northwest');
hline = icons(2);
linedata = get(hline,'xdata');
newdata = [linedata(1)+0.2 linedata(2)];
set(hline,'xdata',newdata,'linewidth',1)
I am using the for loop to plot these figures because I have multiple figures to analysis at the same time. Now I can change the length of the legend line right now. But I got another problem: if I have different length of legend text, even if I set the same starting point and end point, I will get different length for the line in the end (you can see that from the figures). I tried to modify icon(1) but always got the error. Any suggestions?
There are 2 things you are not doing right with your code (aside the fact that you use size as the handles to the legend...that's risky because size is a built-in function):
1) Calling legend with only 1 argument returns a handle to the legend object and getting its position actually gives you the position of the box enclosing the legend, i.e. the text + the line.
2) Using this line:
p(3) = p(3) - 0.06;
does modify the position, however you would need to set the new position of the legend with something like the following for the changes to be effective:
set(HandleToLegend,'Position',p)
To come back to your question, the trick is to assign many outputs during the call to legend; you can then modify specific elements of the legend object.
Actually we only need 1 of the 4 output arguments, called icons in the docs so I'll stick with the notation. Then, we can get the XData property of the line and modify it as we want. The XData is actually a 2-element vector:
[StartingPoint EndingPoint]
so changing one or the other (or both) will change the length of the line displayed in the legend box.
Here is the whole code with comments; I changed the length and linewidth of the line in the 2nd plot to highlight the changes.
clear
clc
close all
x = 1:10;
y = rand(1,10);
figure;
%// Default case
subplot(1,2,1)
plot(x,y);
legend('First plot','Location','NorthWest');
title('Before','FontSize',18);
%// With modifications
subplot(1,2,2)
plot(x,y);
title('After','FontSize',18);
%//========================
%// Change the legend here
%//========================
%// The "icons" output is what you want
[~,icons,~,~] = legend('First plot','Location','NorthWest');
%// icons(1) is the text of the current element in the legend Here its 'First plot'
i_1 = get(icons(1)); %// access the properties with this command.
%// icons(2) is the line associated with that text. Here the blue line.
i_2 = get(icons(2));
%// Mhh I don't know what icons(3) represents haha sorry about that.
i_3 = get(icons(3));
%// Get the actual line
hline = icons(2);
%// Fetch its XData property
LineData = get(hline,'XData')
%// Play with those 2 elements to see the output change.
NewData = [LineData(1)+.2 LineData(2)-.01];
%// Apply the changes
set(hline,'XData',NewData,'LineWidth',3)
Which gives the following:
You need to set the value of the Position property, you can just change the vector p. p does not affect the plot at all, it's just a vector of numbers. You have to modify it, then apply it back to the plot, using
set(size,'Position',p)
There does seem to be a minimum width of the legend however.

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

Matlab - how to make a custom legend

I have the following picture :
And I would like to make a legend for it. Basically, I want to make a legend for each type of rectangle. In the legend box, I want to mark each color line according to the type of body which it marks:
green line : head
yellow line : torso
purple line : right arm
cyan line : left arm
red line : left leg
blue line : right leg
This is basically custom, because I have more rectangles of each type. How can I do a custom legend and attach it to the figure which draws this picture?
There are 2 ways you could go about this. You could create your squares and then assign them to an hggroup. This way you dont have multiple items for each color. Something like this:
hold on
for ii = 1:4
hb(ii) = plot(rand(1,2), rand(1,2),'color','r');
end
hg = hggroup;
set(hb,'Parent',hg)
set(hg,'Displayname','Legs')
legend(hg)
Or you could create dummy objects, like this:
hold on
for ii = 1:4
hb(ii) = plot(rand(1,2), rand(1,2),'color','r');
end
p = plot([],[],'r');
legend(p,'Legs')
The former is a little more elegant.
I would like to add to dvreed77's answer on using hggroup that for clean legend use, I also needed to set the 'IconDisplayStyle' (Matlab R2014a), such that:
%4 kinds of lines:
n_areas = 4;
n_lines = 10;
%use built-in color map
cmap = hsv(n_areas);
%plot lines and generate handle vectors
h_fig = figure;
hold on
h_lines = zeros(1,n_lines);
for l = 1:n_areas
for k = 1:n_lines
h_lines(k) = plot(rand(1,2), rand(1,2),'Color',cmap(l,:));
end
%Create hggroup and set 'icondistplaystyle' to on for legend
curPlotSet = hggroup;
set(h_lines,'Parent',curPlotSet);
set(get(get(curPlotSet,'Annotation'),'LegendInformation'),...
'IconDisplayStyle','on');
end
%Now manually define legend label
legend('heads','legs','hands','feet')
The simplest way I can think of is to first plot one rectangle of each type and construct a legend for only unique rectangles. Like so:
figure;
hold on;
% unique rectangles
plot(rand(1, 10), 'b');
plot(rand(1, 10), 'g');
% the rest
plot(rand(1, 10), 'b');
plot(rand(1, 10), 'g');
% use normal legend with only as many entries as there are unique rectangles
legend('Blue', 'Green');
You will have many lines of the same color, but a legend only for unique colors.
Just draw legend dots outside the plot:
figure;
plot(-1,-1,'gs',-1,-1,'b^',-1,-1,'ro');
legend('x1','x2','x3','Location','NorthWest');
xlim([0,1]); ylim([0,1]);
To control the appearance of legend entries, plot points that have values which are NaN then pass the objects returned by plot and an array of labels to the legend function (NaN points are not visible in the plot, but appear in the legend).
colors = ["red", "blue"];
labels = ["this is red", "this is blue"];
% We 'plot' a invisible dummy point (NaN values are not visible in plots),
% which provides the line and marker appearance for the corresponding legend entry.
p1 = plot(nan, nan, colors(1));
hold on
p2 = plot(nan, nan, colors(2));
% Plot the actual plots. You can change the order of the next two function calls
% without affecting the legend.
plot([0, 1], [0, 1], colors(1));
plot([0, 1], [1, 0], colors(2));
legend([p1, p2], labels)
If the plots in [p1, p2] are not in the current figure when legend([p1, p2], labels) is called, then it will raise the following error:
Invalid argument. Type 'help legend' for more information.
You can filter plots that are not in the current figure using something like this:
plots_in_figure = findall(gcf,'Type','Line');
plots_for_legend_indices = ismember([p1, p2], plots_in_figure);
plots_for_this_legend = this.plots_for_legend(plots_for_legend_indices);
legend(plots_for_this_legend, labels)