How to plot multiple plot in the same figure inside for-loop
4 次查看(过去 30 天)
显示 更早的评论
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 个评论
fred ssemwogerere
2020-2-5
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.
采纳的回答
Jakob B. Nielsen
2020-2-5
编辑:Jakob B. Nielsen
2020-2-10
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 个评论
Jakob B. Nielsen
2020-2-10
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 :)
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Annotations 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!