How to plot multiple plot in the same figure inside for-loop

3 views (last 30 days)
Hi,
I have data of 15 participants. In my for loop, I import data for each participant and I calculate some values (like speed, acceleration, and so on).
I would like to plot "speed to time" figure for each participant in the same figure BUT I don't keep in an unique matrix all the variables from participant (i.e at each loop my variable timerLog and speedz were removed).
I can't share my code because I load my data from confidential folder but I could simulate what I've done :
% Data from Participant 1
timerLog=rand([5 1]);
speedz=rand([5 1]);
% Plot for Participant 1
Fig=figure;
hold on
plot(timerLog,speedz);
xlabel('Time')
legend('location','southeast')
title ('Speed z')
axis tight
% Next loop import data from Participant 2
timerLog=rand([5 1]);
speedz=rand([5 1]);
% Plot for Participant 2
Fig=figure;
hold on
plot(timerLog,speedz);
xlabel('Time')
legend('location','southeast')
title ('Speed z')
axis tight
%% I would like to have Plot for Participant 2 in the same figure than Participant 1
Thank you very much for your help,
Anne-Laure
  1 Comment
fred  ssemwogerere
fred ssemwogerere on 5 Feb 2020
Hello, is your data for the different participants stored in different files?
If so, you can make use of "fileDatastore", from which you can read the contents of different files in a loop, while plotting the results on the same axes. 'figure' should be initiated at the beginning of the loop, and 'hold on' at the end of the loop for plots to appear on the same axes.

Sign in to comment.

Accepted Answer

Jakob B. Nielsen
Jakob B. Nielsen on 5 Feb 2020
Edited: Jakob B. Nielsen on 10 Feb 2020
If hold on is used, matlab will add plot commands to the active axes (or active figure, if you will), unless you specify otherwise. If hold off, it will replace the graphics. So in order to achieve what you want, simply initialise a single figure outside of your loop, and then set hold on like you also do. Then reference that figure for all your plots.
Fig=axes;
hold on %the key.
% Data from Participant 1
timerLog=rand([5 1]);
speedz=rand([5 1]);
% Plot for Participant 1
plot(Fig,timerLog,speedz);
xlabel('Time')
legend('location','southeast')
title ('Speed z')
axis tight
% Next loop import data from Participant 2
timerLog=rand([5 1]);
speedz=rand([5 1]);
% Plot for Participant 2
plot(Fig,timerLog,speedz);
xlabel('Time')
legend('location','southeast')
title ('Speed z')
axis tight
  7 Comments
Jakob B. Nielsen
Jakob B. Nielsen on 10 Feb 2020
Have you remembered the hold on? I edited the code in my first post to remove all the unneeded stuff. When I run it, it gives two plots in one figure just fine :)

Sign in to comment.

More Answers (0)

Categories

Find more on 2-D and 3-D Plots in Help Center and File Exchange

Tags

Products


Release

R2019a

Community Treasure Hunt

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

Start Hunting!