I would like to add points "live" to a scatter plot in matplotlib, so that the points appear on the graph as soon as they are computed. Is it possible? If not, is there a python-compatible similar plotting platform where this can be done? Thanks!
1 Answer
You can append new points to the offsets array of the return value of ax.scatter.
You need to make the plot interactive with plt.ion() and update the plot with fig.canvas.update().
This draws from a 2d standard normal distribution and adds the point to the scatter plot:
import matplotlib.pyplot as plt
import numpy as np
plt.ion()
fig, ax = plt.subplots()
plot = ax.scatter([], [])
ax.set_xlim(-5, 5)
ax.set_ylim(-5, 5)
while True:
# get two gaussian random numbers, mean=0, std=1, 2 numbers
point = np.random.normal(0, 1, 2)
# get the current points as numpy array with shape (N, 2)
array = plot.get_offsets()
# add the points to the plot
array = np.append(array, point)
plot.set_offsets(array)
# update x and ylim to show all points:
ax.set_xlim(array[:, 0].min() - 0.5, array[:,0].max() + 0.5)
ax.set_ylim(array[:, 1].min() - 0.5, array[:, 1].max() + 0.5)
# update the figure
fig.canvas.draw()
5 Comments
geodude
It works. How can I make the graph rescale automatically, though? Thanks!
pceccon
How do you can set the color for each of these points? In my case, I have a predefined scatter plot and I'd like to plot the new points with a new color. Thanks.
MaxNoe
there is also
set_colorHelena
I get this error - 'vertices' must be a 2D list or array with shape Nx2. I am using Python 3. Also getting "too many indices for array" from ax.set_xlim..." line
Marcus
I also get the "too many indices for array" error. Changing the 1st append command to
array = np.append(array, [point], axis=0) fixes this.