Issue
In previous versions of my code I cleared the plot and replotted the data up until the most recently calculated data point. In an attempt to speed up the plotting, I am trying to switch to using set_data
so I am not clearing every step. Unfortunately, I am unable to produce a line with this change.
Below you can see my attempt at using set_data
for the top plot, but I left the original method for the bottom one.
Please let me know how I can fix this issue.
import matplotlib.pyplot as plt
import numpy as np
plt.close("all")
frames = 200
x = np.linspace(0, 4*np.pi, frames)
y1 = np.sin(x)
y2 = np.cos(x)
fig, (ax1, ax2) = plt.subplots(2, 1)
line1, = ax1.plot([], [])
line2, = ax2.plot([], [])
ax1.set_xlim(x.min()*1.1, x.max()*1.1)
ax1.set_ylim(y1.min()*1.1, y1.max()*1.1)
def animate(i):
line1.set_data(x[i], y1[i])
ax2.cla()
ax2.plot(x[:i], y2[:i])
ax2.set_xlim(x.min()*1.1, x.max()*1.1)
ax2.set_ylim(y2.min()*1.1, y2.max()*1.1)
plt.pause(0.01)
for i in range(20*frames):
animate(i%frames)
Solution
My mistake with this problem was a pretty basic mistake and was based on misunderstanding the use of the set_data
function. I thought that I needed to pass into it a new data point, but really you need to pass the entire data set, but with updated points.
So, the code ended up looking as follows:
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import numpy as np
plt.close("all")
frames = 200
x = np.linspace(0, 4*np.pi, frames)
y1 = np.sin(x)
y2 = np.cos(x)
fig, (ax1, ax2) = plt.subplots(2, 1)
line1, = ax1.plot([], [])
line2, = ax2.plot([], [])
ax1.set_xlim(x.min()*1.1, x.max()*1.1)
ax1.set_ylim(y1.min()*1.1, y1.max()*1.1)
def animate(i):
line1.set_data(x[:i], y1[:i])
ax2.cla()
ax2.plot(x[:i], y2[:i])
ax2.set_xlim(x.min()*1.1, x.max()*1.1)
ax2.set_ylim(y2.min()*1.1, y2.max()*1.1)
plt.pause(0.01)
for i in range(20*frames):
animate(i%frames)
And, as suggested by @Lutz Lehmann in the comments, I could do this pretty easily using FuncAnimation
, as shown below.
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import numpy as np
plt.close("all")
frames = 200
x = np.linspace(0, 4*np.pi, frames)
y1 = np.sin(x)
y2 = np.cos(x)
fig, (ax1, ax2) = plt.subplots(2, 1)
line1, = ax1.plot([], [])
line2, = ax2.plot([], [])
for ax in (ax1, ax2):
ax.set_xlim(x.min()*1.1, x.max()*1.1)
ax.set_ylim(y1.min()*1.1, y1.max()*1.1)
def animate(i):
line1.set_data(x[:i], y1[:i])
line2.set_data(x[:i], y2[:i])
return (line1, line2),
anim = FuncAnimation(fig, animate, frames=frames, interval=0.01)
Answered By - jared
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.