[Matplotlib-users] Plot

Scott Lasley selasley at icloud.com
Wed Aug 14 15:15:51 EDT 2019


Hi Partha,

This stackoverflow answer should help you do what you want
https://stackoverflow.com/questions/10944621/dynamically-updating-plot-in-matplotlib

Here is some similar code.  Run the code between the ...'s in a Jupiter notebook cell to create the first empty plot
...

# comment out this line if you are not running this in a jupyter notebook
%matplotlib notebook

import numpy as np
from matplotlib import pyplot as plt


def update_points(fig, pts, new_data):
    # get the data for the points in the current plot
    pts_data = pts.get_data()
    # update the points using set_data with the 
    # new_data values appended to the current values
    pts.set_data(np.append(pts_data[0], [new_data[0]]),
                 np.append(pts_data[1], [new_data[1]]))
    # update the plot
    fig.canvas.draw_idle()
    # uncomment the next two lines if you want the plot to
    # automatically adjust its limits when you add data
#     ax.relim()
#     ax.autoscale_view(scaley=True)
    return


# create a figure
# if you are running the code in ipython you may need to 
# call plt.ion() after creating the figure
fig, ax = plt.subplots()

# set the plot's x and y limits if you know the range 
# of the data you will generate.  otherwise let 
# update_plot adjust the limits
ax.set(xlim=[0,100], ylim=[0,100])

# plot an empty list to create the pts Line2D array 
# with no data
pts = ax.plot([], 'o')[0]

...

Then in the next cell(s) call update_points for each new data point to be plotted

...
new_data = [10, 10]
update_points(fig=fig, pts=pts, new_data=new_data)
...
new_data = [20, 40]
update_points(fig=fig, pts=pts, new_data=new_data)
...

Hope this helps,
Scott

> On Aug 14, 2019, at 12:47 AM, Partha Sinha <pnsinha68 at gmail.com> wrote:
> 
> I got the solution as suggested by scott. 
> My new problem is:
> Lets say I will generate lets  two pairs of 10 random numbers, say x and y.
> When first pair of x and y is generated, it will be plotted. Again when second set of number is generated, it will appear on the same graph and not on 2nd graph.
> This will continue till 10th pair.
> How to do this?
> Regards
> Parth



More information about the Matplotlib-users mailing list