Legend containing only specific plots - matlab

I have 10 curves in a plot, but only three of them should appear in the legend. For example, among 10 curves, just the first, 5th and 10th should be in the legend, how I can do this?
Here's my program:
x=1:0.5:15;
y1=x.^1
plot(x,y1)
hold on
y2=x.^1.2
plot(x,y2)
hold on
.
.
.
y10=x.^2.2
plot(x,y10)

You can use handles for the plots, and then specify the plots for the legend by their handles:
x=1:0.5:15;
y(1,:)=x.^1;
y(2,:)=x.^1.2;
...
...
...
y(10,:)=x.^2.2;
for k=1:10
h(k)=plot(x,y(k,:));
hold on
end
legend([h(1) h(5) h(10)],'curve 1','curve 5','curve 10');
hold off

legend can take a handle or handles, and a list of strings. I've taken the liberty of rewriting your code so it plots in a loop rather than creating a bunch of y variables. Generally speaking, if you find yourself creating a series of variables named y1, y2, etc, there's a better way of doing it in MATLAB.
There are 7 plots, not 10, but you get the idea.
x=1:0.5:15;
m=1:0.2:2.2;
figure
hold on
for n = 1:7
h(n) = plot(x,x.^m(n));
end
legend(h([1,3,5]),'Plot One', 'Plot Three', 'Plot Five',...
'Location', 'NorthWest')

you need to use the plot handles in the legend function to indicate the desired curves. Inserted in your code it would look like this:
x=1:0.5:15;
y1=x.^1;
h1=plot(x,y1,'r');
hold on
y2=x.^1.2;
h2=plot(x,y2,'c');
hold on
.
.
.
y10=x.^2.2;
h10=plot(x,y10,'p');
hold off;
legend([h2,h10] , 'Fart 2', 'More Fart'); % Plot in the handle you wish

Here's a slick two-liner that I use:
a=flipud(findall(gcf,'Type','Line')); %get all line objects of current plot
legend(a([1 3]),{'a','b'}) %add legend for line 1 and 3, 'a' and 'b'

The legend command only applies to the most recent created plot, unless a handle is passed.
figure
for c=1:10
subplot(4,4,c)
ezplot('y=sin(x)');
if c==5||c==10
legend('sin(x)')
end
end

Related

matlab adding single legend for multiple data

figure(1);
hold on;
na=4;
circle_X = [0 0 5 5]';
circle_Y = [0 3 0 3]';
for a = 1:na
r=0.3;
N=100;
theta=linspace(0, 2*pi, N);
cx=r*cos(theta)+circle_X(a);
cy=r*sin(theta)+circle_Y(a);
plot3(cx , cy, 300*ones(N), 'r', 'linewidth', 2,'DisplayName',sprintf('circle'));
end
legend('show');
I want to draw 4 circles and add a single legend 'circle' indicating 4 circles all at once, without using "legend('circle')".
For now the legend looks like this
how should I change the code?
First, you don't need plot3, you can achieve the same figure with plot, and probably the long legend is because of that.
just change the line of plot to that:
plot(cx , cy, 'r', 'linewidth', 2,'DisplayName','circle');
Now, the legend will have 4 entries because you draw four objects. If you want a single entry you have some ways:
add the legend inside the loop, after an if statement. For example,
if a==1 ,
legend('show');
end
get handles for your plots, and legend just one of them. It can be done directly from legend, but then you will need to specify the string:
for....
h(a)=plot...
end
legend(h(1),'circle')
get handles like in part 2, and if you don't want specify the string 'circle', you can use the undocumented hasbehavior:
for...
h(a)=plot...
end
hasbehavior(h(2),'legend',false);
hasbehavior(h(3),'legend',false);
hasbehavior(h(4),'legend',false);
l=legend('show');

Two point series on the same graph on MatLab

I want to draw two separated lines, but I get the two lines on two points. How do I draw them separated?
When you implement the code, the green line should start from point 3 and end in point 4 on the x-tick. But, it starts again from point 1 and end in point2.
%% My question code:
a=3; %point1
b=4; %point2
c=6; %point3
d=7; %point4
plot([a b], 'k- *');
hold on;
plot([c d], 'g- *');
hold off
set(gca, 'XTick', 1:4, 'XTickLabel', {'point1', 'point2', 'point3','point4'})
axis([0 10 0 10]);
When you hold the current plot and plot a new one. x axis values are taken as if it is the first plot. To avoid the confusion, specify values for both x and y axes.
So change your plot commands like this:
plot([1,2], [a,b], 'k- *');
hold on;
plot([3,4], [c,d], 'g- *');
hold off;
or combine two plot commands into a single one like this:
plot([1,2], [a,b], 'k- *', [3,4], [c,d], 'g- *');

Matlab legend for two plots only applies to second plot

I need to plot data of two vectors, and want the data points of each to be shown in a different colour that is explaned in a legend. However, the code below displays only the legend for the second one. What am I doing wrong?
for i_plot = 1 : plot_step : N
subplot(N, 1, i_plot)
h_A = plot(bookmarksA(i_plot, :),0,'b.','MarkerSize',24);
legend('a');
xlim ([0 pieceDuration])
set(gca, 'yTick', []);
title(subj_string(i_plot,:))
hold on
h_Z = plot(bookmarksZ(i_plot, :),0,'r.','MarkerSize',24);
legend(h_Z, 'z');
end
You're only passing one label / handle combination to the legend command at a time. For a given axes, each call to legend overrides previous calls to legend, deleting previous legends rather than adding to an existing legend. You'll want to call legend once with both plot handles and labels.
legend([h_A, h_Z], {'a', 'z'})
Update
Since in your case h_A and h_Z are arrays of plot handles with identical appearances, you can just pass the first item from h_A and h_Z to legend.
legend([h_A(1), h_Z(1)], {'a', 'z'})

MATLAB graph plotting: assigning legend labels during plot

I am plotting data in a typical MATLAB scatterplot format. Ordinarily when plotting multiple datasets, I would use the command 'hold on;', and then plot each of the data, followed by this to get my legend:
legend('DataSet1', 'DataSet2') % etcetera
However, the (multiple) datasets I am plotting on the same axes are not necessarily the same datasets each time. I am plotting up to six different sets of data on the same axes, and there could be any combination of these shown (depending on what the user chooses to display). Obviously that would be a lot of elseif's if I wanted to setup the legend the traditional way.
What I really would like to do is assign each DataSet a name as it is plotted so that afterwards I can just call up a legend of all the data being shown.
...Or, any other solution to this problem that anyone can think of..?
You should be able to set the DisplayName property for each plot:
figure
hold on
plot(...,'DisplayName','DataSet1')
plot(...,'DisplayName','DataSet2')
legend(gca,'show')
http://www.mathworks.com/help/matlab/ref/line_props.html
Side Note: I've found a lot of little tricks like this by getting the figure to look the way I want, then choosing the Figure's "File" menu option "Generate M-File..." and inspecting the generated output code.
One option is to take advantage of the 'UserData' property like so:
figure;
hold on
plot([0 1], [1 0], '-b', 'userdata', 'blue line')
plot([1 0], [1 0], '--r', 'userdata', 'red dashes')
% legend(get(get(gca, 'children'), 'userdata')) % wrong
legend(get(gca, 'children'), get(get(gca, 'children'), 'userdata')) % correct
Edit: As the questioner pointed out, the original version could get out of order. To fix this, specify which handle goes with which label (in the fixed version, it is in the correct order).
Use 'DisplayName' as a plot() property, and call your legend as
legend('-DynamicLegend');
My code looks like this:
x = 0:h:xmax; %// get an array of x-values
y = someFunction; %// function
plot(x, y, 'DisplayName', 'Function plot 1'); %// plot with 'DisplayName' property
legend('-DynamicLegend',2); %// '-DynamicLegend' legend
Source: http://undocumentedmatlab.com/blog/legend-semi-documented-feature/
You can try something like the following
for k = 1:10
h(k) = plot(...);
name{k} = ['condition ' num2str(k)];
end
legend(h, name);
Make a for loop. But Before the for loop, make an array.
%for example
legendset = {}
for i = 1:10
%blabla
%Then in the fore loop say:
legendset = [legendset;namedata(i)]
%It puts all names in a column of legendset.
%Make sure namedata are characters.
%foreloop ends
end
%Then after the foreloop say:
legend(legendset).

How to plot two figures in MATLAB

I am implementing a clustering algorithm for n data points and I want to plot n data points in a figure before clustering and in another figure after clustering meaning that there should be two figures in same file with same data points.
My code is like:
X = 500*rand([n,2]);
plot(X(:,1), X(:,2), 'r.') 1
%Some coding section here
After:
symbs = {'r+','g.','bv','m*','ko'};
hold on
for i = 1: length(I)
plot(X(C==i,1), X(C==i,2), symbs{i}) 2
end
I just want to plot (1) in one figure and (2) in another.
Try subplot:
figure;
subplot(1,2,1)
plot(firstdata)
subplot(1,2,2)
plot(seconddata)
This will create two axes areas within the same figure window... from your description, this is my best guess as to what you want.
Edit: From the comments below, here is what you are doing
n=50;
X = 500*rand([n,2]);
subplot(1,2,1); #% <---- add 'subplot' here
plot(X(:,1),X(:,2),'r.')
symbs= {'r+','g.','bv','m*','ko'};
subplot(1,2,2); #% <---- add 'subplot' here (with different arguments)
hold on
for i = 1: length(I)
plot(X(C==i,1),X(C==i,2),symbs{i})
end
If all you want is a second figure window, instead of doing subplot you can simply say figure in the place where I put the second call to subplot and a new figure window will be created.
figure; #% <--- creates a figure window
n=50;
X = 500*rand([n,2]);
plot(X(:,1),X(:,2),'r.') #% <--- goes in first window
symbs= {'r+','g.','bv','m*','ko'};
figure; #% <---- creates another figure window
hold on
for i = 1: length(I)
plot(X(C==i,1),X(C==i,2),symbs{i}) #% <--- goes in second window
end
You just need to add figure before each plot to get two plots in two separated figures