How can I plot multiple lines in different colors on a single plot using loops?
Mostrar comentarios más antiguos
I am evaluating and plotting a function of time using at multiple times using a for loop and I want each line to plot a different color. My code plots all the lines the same color. At first my legend was not matching the lines so I am trying to plot the lines with defined colors and then change my legend accordingly. If anyone knows why the legends colors are out of order with the plot that would also help!
Cs is the function that varies with time.
Can someone suggest another way of doing this?
line_color = ['b' 'g' 'y' 'c' 'm' 'r'];
for i=1:length(t);
figure(1)
title('Carbon Sequestration in Indoor Environment vs. SA/V Ratio','FontSize',10)
ylabel('Carbon Sequestration (kg CO2)')
xlabel('SA/V Ratio')
legend('25 years','50 years','75 years','100 years','125 years','150 years','AutoUpdate','off')
hold on
plot(SAV_ratio,Cs,line_color(i),'LineWidth',2)
end
Thanks
3 comentarios
Is this only a small part of the loop? Because as it stands now, the loop seems rather meaningless. Second, you are plotting the entire set of data in every loop, with different colors. You probably have a lot more line handles than you desire. Finally, always save handles to the plot, especially when plotting in a loop.
h{i}=plot(SAV_ratio,Cs,line_color(i),'LineWidth',2)
JoelB
el 15 de Sept. de 2018
Image Analyst
el 15 de Sept. de 2018
Joel, did you even see my answer below in the official "Answer" section of this page?
Respuesta aceptada
Más respuestas (2)
Image Analyst
el 15 de Sept. de 2018
Try this. Adapt as needed for your signal.
line_color = ['b' 'g' 'y' 'c' 'm' 'r'];
t = 1 : 100;
SAV_ratio = t;
ca = cell(1, length(line_color));
period = 100;
for k = 1 : length(line_color)
ca{k} = sprintf('%d years', k*25);
hold on
% Get new values.
Cs = sin(2*pi*t / (period * k));
plot(SAV_ratio, Cs,'-', 'Color', line_color(k),'LineWidth',2)
grid on;
end
title('Carbon Sequestration in Indoor Environment vs. SA/V Ratio','FontSize',16)
ylabel('Carbon Sequestration (kg CO2)')
xlabel('SA/V Ratio')
ax = gca;
ax.XAxisLocation = 'origin';
legend(ca, 'Location', 'southwest')

Ivan Popov
el 16 de Jun. de 2021
Editada: Ivan Popov
el 16 de Jun. de 2021
2 votos
You have to use colororder(Colormap Name) with the desired color map. Then with one plot, you can use all desired colors in the appropriate order. Actually one can change colororder after data is plotted.
Example:
colororder(hsv(x));
plot(AnyMatrix(:,1:x));
1 comentario
Adam Danz
el 14 de Jun. de 2022
Categorías
Más información sobre Graphics Performance en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

