Question

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)
Was it helpful?

Solution

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

OTHER TIPS

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

enter image description here

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top