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!

1
  • 2
    Are you looking for this? Commented Sep 18, 2015 at 12:16

1 Answer 1

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()
Sign up to request clarification or add additional context in comments.

5 Comments

It works. How can I make the graph rescale automatically, though? Thanks!
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.
there is also set_color
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
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.