Plotting with a for loop

1 view (last 30 days)
EYKL
EYKL on 24 Sep 2021
Commented: Cris LaPierre on 25 Sep 2021
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-');

Accepted Answer

Cris LaPierre
Cris LaPierre on 24 Sep 2021
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 Comments
EYKL
EYKL on 25 Sep 2021
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 on 25 Sep 2021
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."

Sign in to comment.

More Answers (0)

Products


Release

R2020b

Community Treasure Hunt

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

Start Hunting!