change the color of data in legend
Show older comments
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
More Answers (1)
Fangjun Jiang
on 21 Jun 2011
0 votes
14 Comments
Hassan
on 21 Jun 2011
Fangjun Jiang
on 21 Jun 2011
Move this line outside of your for-loop. Currently it was executed twice.
plot([0 10],[5 5],'g');
Fangjun Jiang
on 21 Jun 2011
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.
Hassan
on 21 Jun 2011
Hassan
on 21 Jun 2011
Walter Roberson
on 21 Jun 2011
Which one? Exactly how many lines do you want to be plotted?
Hassan
on 21 Jun 2011
Fangjun Jiang
on 21 Jun 2011
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.
Fangjun Jiang
on 21 Jun 2011
Then use legend('plot1','line','plot2','line2'), two green lines still match, right?
Hassan
on 21 Jun 2011
Walter Roberson
on 21 Jun 2011
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.
Hassan
on 21 Jun 2011
Hassan
on 21 Jun 2011
aerothermal
on 31 Aug 2016
Same answer of https://www.mathworks.com/matlabcentral/answers/146668-legend-and-graph-doesn-t-have-the-same-color
By the way, nice work!
Categories
Find more on Legend in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!