5

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!

geodude
  • 221
  • 1
  • 2
  • 7

1 Answers1

9

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()
MaxNoe
  • 14,470
  • 3
  • 41
  • 46
  • It works. How can I make the graph rescale automatically, though? Thanks! – geodude Sep 19 '15 at 19:52
  • 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. – pceccon Oct 27 '16 at 18:38
  • there is also `set_color` – MaxNoe Oct 28 '16 at 08:38
  • 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 – Helena Dec 05 '18 at 14:13
  • 3
    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. – Marcus Mar 30 '20 at 12:06