MATLAB Answers

Plotting two graphs simultaneously in a for loop

7 views (last 30 days)
mobius
mobius on 28 Mar 2020
Edited: mobius on 28 Mar 2020
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

  3 Comments

Tommy
Tommy on 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.
mobius
mobius on 28 Mar 2020
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

Sign in to comment.

Answers (0)

Sign in to answer this question.


Translated by