Plotting with a for loop

4 次查看(过去 30 天)
Hello all,
I was wondering if it was possible to use a for loop to plot certain lines on my figures. For example, my 1st plot will contain all 4 lines while my 2nd plot will omit the very 1st line in my 1st plot and only plot the remaining 3 lines. My 3rd plot will then omit the first 2 lines and only plot the remaining 2 lines. Instead of adding the code manually, is there a simpler approach?
% % x,y,z,a,b = My datasets
tiledlayout(3,1);
figure;
nexttile; % 1st plot with all 4 lines
plot(x,y,'r-');
hold on;
plot(x,z,'b-');
hold on;
plot(x,a,'k-');
hold on;
plot(x,b,'k-');
nexttile; % 2nd plot with 3 lines
plot(x,z,'b-');
hold on;
plot(x,a,'k-');
hold on;
plot(x,b,'m-');
nexttile; % 3rd plot with 2 lines
plot(x,a,'k-');
hold on;
plot(x,b,'m-');

采纳的回答

Cris LaPierre
Cris LaPierre 2021-9-24
If your variables y,z,a & b are column vectors (and if they are not, you could easily make them column vectors), you could do the following
x = 1:10;
data = rand(10,4); % data = [y,z,a,b];
cspec = {'r','b','k','m'};
tiledlayout(3,1);
ax1 = nexttile; % 1st plot with all 4 lines
plot(x,data(:,1:4));
colororder(ax1,cspec(:));
ax2 = nexttile; % 2nd plot with 3 lines
plot(x,data(:,2:4))
colororder(ax2,cspec(2:end));
ax3 = nexttile; % 3rd plot with 2 lines
plot(x,data(:,3:4))
colororder(ax3,cspec(3:end));
  2 个评论
EYKL
EYKL 2021-9-25
Hi @Cris LaPierre, I noticed you used colororder to fix the colours of the plots. Is there a way I can do this with point markers and linetype? For example:
%1st line = '-rx';
%2nd line = '-bo';
%3rd line = '-g+';
Also, I didn't know colororder existed. I learned something new today. Thanks.
Cris LaPierre
Cris LaPierre 2021-9-25
There is, but there is not a helper function for that purpose. You must manually set the properties of the axes. The property you want is LineStyleOrder, which allows you specify both line and marker style. However, take note of this comment on how LineStyleOrder works:
"MATLAB assigns styles to lines according to their order of creation. It changes to the next line style only after cycling through all the colors in the ColorOrder property with the current line style."

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Annotations 的更多信息

标签

产品


版本

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by