2

I am updating the graph, but can't join to it the scatter, could someone help me, please? I don't understand, how to realize it.

from matplotlib import pyplot as plt from matplotlib.animation import FuncAnimation fig = plt.figure() ax = fig.add_subplot() line = ax.plot([],[])[0] x = [] y = [] scat = ax.scatter(x,y,c='Red') def animate(i): x.append(i) y.append((-1)**i) line.set_data(x, y) ax.relim() ax.autoscale_view() return [line] anim = FuncAnimation(fig, animate, frames=200, interval=100, blit=True) plt.show() 

I want to add dotes and their coordinates change only in X, Y should be 0.

enter image description here

1 Answer 1

2

Several problems have to be addressed here. You have to update the scatter plot, which is a PathCollection that is updated via .set_offsets(). This is in turn requires the x-y data to be in an array of the form (N, 2). We could combine the two lists x, y in every animation loop to such an array but this would be time-consuming. Instead, we declare the numpy array in advance and update it in the loop. As for axes labels, you might have noticed that they are not updated in your animation. The reason for this is that you use blitting, which suppresses redrawing all artists that are considered unchanged. So, if you don't want to take care manually of the axis limits, you have to turn off blitting.

from matplotlib import pyplot as plt from matplotlib.animation import FuncAnimation import numpy as np fig, ax = plt.subplots() line, = ax.plot([],[]) scat = ax.scatter([], [], c='Red') n=200 #prepare array for data storage pos = np.zeros((n, 2)) def animate(i): #calculate new x- and y-values pos[i, 0] = i pos[i, 1] = (-1)**i #update line data line.set_data(pos[:i, 0], pos[:i, 1]) #update scatter plot data scat.set_offsets(pos[:i, :]) #update axis view - works only if blit is False ax.relim() ax.autoscale_view() return scat, line anim = FuncAnimation(fig, animate, frames=n, interval=100, blit=False) plt.show() 

Sample output: enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.