Plotting two graphs simultaneously in a for loop
Afficher commentaires plus anciens
Hey guys,
I have a set of data and would want to plot the data points like an animation using a for-loop. This is my code:
figure(1)
for k = 1:5000
%plotX is a 1x5000 dimension vector with elements 1,2,3,...,N
%hmid2 and hamid2 are 1x5000 dimension vector
hplot = plot(plotX(k),hmid2(k),'.b',plotX(k),hamid2(k),'-r');
hold on
xlim([0 N_iter*Lx]);
drawnow
k
end
I am hoping to get a graph like this, but in animation:

Instead, what I got from my animation is:

The lines connecting them disappeared, and the 2nd graph, denoted by hamid2 does not appear in the animated graph.
I'm a newbie so I wonder if there's something I missed out or mistaken?
Cheers
4 commentaires
Tommy
le 28 Mar 2020
In each of your calls to plot(), you are plotting single values. The values plotted in one iteration won't connect to the values plotted in the previous iteration. This is fine for your blue plot, because you set the markers to points, which is why you can see the blue plot. The red plot, however, is not showing at all because you did not set the marker, instead you set the line style to solid. Note the difference between these two, where I'm plotting single values:
>> plot(1,1,'-') % line style set to solid
>> plot(1,1,'.') % marker set to point
You will be able to visualize both plots if you instead pass arrays into plot(). In each iteration, try plotting all values from 1 through k:
hplot = plot(plotX(1:k),hmid2(1:k),'.b',plotX(1:k),hamid2(1:k),'-r');
and taking out the hold on.
Walter Roberson
le 28 Mar 2020
Or use animatedline()
APU CHAKRABORTY
le 7 Juin 2022
how to plot three graphs using subplots ,animitedline and adpoint?
Réponses (1)
Mathieu NOE
le 7 Juin 2022
hello
using your x and y data , see answer (example) below :
%% create animatedline object / handle
figure
h1 = animatedline;
h1.Marker = '*';
h1.Color = [1 0.4 0];
h2 = animatedline;
h2.Marker = '+';
h2.Color = [0 1 0];
axis([0 5 -1.2 1.2]);
%% dummy data
x = linspace(0,2*pi,100);
y1 = sin(x);
y2 = cos(x);
for ci=1:length(x)
addpoints(h1,x(ci),y1(ci));
addpoints(h2,x(ci),y2(ci));
pause(0.1);
drawnow
end
3 commentaires
Nikolaos Gkiouzelis
le 21 Sep 2022
Hello,
what if I want the animated lines h1 and h2 to be printed in different figures or subfigures?
Mathieu NOE
le 21 Sep 2022
Nikolaos Gkiouzelis
le 21 Sep 2022
Modifié(e) : Nikolaos Gkiouzelis
le 21 Sep 2022
Thanks a lot.
Could you recommend anything regarding legends, titles and lables as well under the same structure?
Update: solved!
You need to firstly state labels, legends and then start the loop.
xlabel(sub1,'Time [d]');
ylabel(sub1,'Distance [Km]');
legend(sub1,'Velocity');
where sub1, sub2 etc stand for the different subplot/figures.
Catégories
En savoir plus sur Animation dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!