How to assign a different color to lines being plotted in a loop?

223 ビュー (過去 30 日間)
farzad 2020 年 5 月 8 日
編集済み: Akihumi 2020 年 5 月 12 日
Hi All
I am plotting n different lines in one single plot. but what I need it to assign a different color ( even random) for each iteration. and then use it as a Legend.
How do I do this ?
  1 件のコメント
Stephen23 2020 年 5 月 12 日
The accepted answer states that line color is determined by the lines colormap. This is not correct.
Line colors are determined by the axes ColorOrder property:
The lines colormap is also defined in terms of the axes ColorOrder.



Akihumi 2020 年 5 月 8 日
編集済み: Akihumi 2020 年 5 月 12 日
* Edits: Sorry for the wrong information about the default line color.
Otherwise, you can try
hold on
randColor = rand(10,3);
for i = 1:10
But the color would be ugly. Instead of rand, you can try other available colormap. For example
hold on
cm = parula(10);
for i = 1:10
plot(x(:,i),y(:,i),'Color', cm(i,:));
  1 件のコメント
Ameer Hamza
Ameer Hamza 2020 年 5 月 8 日
A correction: By default, the color of lines are chosen from ColorOrder property of the axes, not colormap:


その他の回答 (1 件)

Isiah Pham
Isiah Pham 2020 年 5 月 8 日
編集済み: Isiah Pham 2020 年 5 月 12 日
You can make a cell array for each color you want and the pull from it
colors = {['red'],['blue']}
for rep = 1:2
plot((x,rep.*x), colors{rep})
This will plot two lines, the first red and the second blue


Find more on Colormaps 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!

Translated by