Plotting two graphs simultaneously in a for loop

6 次查看(过去 30 天)
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 个评论
mobius
mobius 2020-3-28
编辑:mobius 2020-3-28
Thank you, Tommy. Your suggestion is really the missing piece I've been looking for.
But the plot line is unclear, and the syntax of plot(x1,y1,x2,y2) does not enable me to include line properties such as 'LineWidth', so I did this:
figure(1)
for k = 1:N_iter*Lx
hplot1 = plot(plotX(1:k),hmid2(1:k),':b','LineWidth',2);
hold on
hplot2 = plot(plotX(1:k),hamid2(1:k),'-r','LineWidth',1.2);
xlim([0 N_iter*Lx]);
drawnow
k
end
The result came out just like what I wanted.
I tried animatedline() as well. This was my code:
figure(1)
%plot the first point first
hplot1 = animatedline(plotX(1),hmid2(1),'Color','b','LineStyle',':','LineWidth',2);
hold on
hplot2 = animatedline(plotX(1),hamid2(1),'Color','r','LineStyle','-','LineWidth',1.2);
xlim([0 N_iter*Lx]); ylim([depth-2*A depth+2*A]);
for k = 2:N_iter*Lx %plot from 2nd point onwards
addpoints(hplot1,plotX(k),hmid2(k));
addpoints(hplot2,plotX(k),hamid2(k));
drawnow
k
end
The result with this animateline() is exactly similar to the previous one, but substantially faster. Thank you Walter!
Cheers
APU CHAKRABORTY
APU CHAKRABORTY 2022-6-7
how to plot three graphs using subplots ,animitedline and adpoint?

请先登录,再进行评论。

回答(1 个)

Mathieu NOE
Mathieu NOE 2022-6-7
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 个评论
Nikolaos Gkiouzelis
编辑:Nikolaos Gkiouzelis 2022-9-21
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.

请先登录,再进行评论。

类别

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

Community Treasure Hunt

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

Start Hunting!

Translated by