change the color of data in legend

I have 3 plots on the same figure but legend doesn't show the right color for each plot.
y=1:10;
color_=['r', 'b'];
for i=1:2
if i==1
j=1;
elseif i==2
j=6;
end
plot(y(j:j+4),color_(i));
hold on
plot([0 10],[5 5],'g');
end
legend('plot1','plot2','line');

 Accepted Answer

h1 = plot(x1,y1,'r');
hold on
h2 = plot(x2,y2,'b');
legend([h1,h2],'plot1','plot2')
The line color used for legend() will be the same as the line color used on the graph.

2 Comments

thanks Walter. sorry I think my question wasn't clear I changed it. could u please look at it.
sice i was using a loop, i did this thing:
h=zeros(2);
colors=['r','g']
for i=1:2
h(i)=plot(x1,y1,colors(i))
legend([h(1),h(2)],'plot1','plot2')
end

Sign in to comment.

More Answers (1)

Fangjun Jiang
Fangjun Jiang on 21 Jun 2011
Follow this post to change the color of the legend.

14 Comments

thanks Fangjun. i edited my question, can u please look at it again.
Move this line outside of your for-loop. Currently it was executed twice.
plot([0 10],[5 5],'g');
Or, put this way, your current code plotted four curves. If you changed the last line to legend('plot1','line','plot2','line2'), the color will match too. Understand that line and line2 are completely overlapping.
I know actually I have 2 lines but want to show them with one color. in this example they put on each other but in my data they are seperat.
so if I put that line (plot([0 10],[5 5],'g');) outside the loop, one of the lone is not plotted.
Which one? Exactly how many lines do you want to be plotted?
2 lines. each line is the mean value of each data.
The bottom line is, there is no problem in the legend() function. If the same number of legend texts are provided and the order matches the order of the curves that are created, the color should all match.
Then use legend('plot1','line','plot2','line2'), two green lines still match, right?
yeah maybe the problem is that. since I have 2 plots and 2 lines. although I'm showing 2 lines with one color but at the same time I need to have 4 texts and 4 colors in the legend.
If you must have the lines be the same color even though they have different meaning, consider using different linestyles for the two. legend() will draw the sample line with the corresponding line style.
As someone reading a graph, it would make little sense to me to have the legend line color be something that did not appear on the graph.
actually the problem is the order of the plots. I am ploting plot 1 and line 1 and then plot 2 and line 2. in the legend i want to have plot1 plot2 and line1/or line 2. so if say legend('plot1','line','plot2'); then its gonna show the color of each plot correctly.
thanks Walter for the help.

Sign in to comment.

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!