Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add points to matlibplot scatter plot live

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!

like image 271
geodude Avatar asked Feb 10 '23 00:02

geodude


1 Answers

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()
like image 110
MaxNoe Avatar answered Feb 13 '23 01:02

MaxNoe