Skip to content Skip to sidebar Skip to footer

Plotting A Continuous Stream Of Data With Matplotlib

I want to use MatPlotLib to plot a graph, where the plot changes over time. At every time step, an additional data point will be added to the plot. However, there should only be on

Solution 1:

(1)

You can set plt.ion() at the beginning and plot all graphs to the same window. Within the loop use plt.draw() to show the graph and plt.pause(t) to make a pause. Note that t can be very small, but the command needs to be there for the animation to work on most backends. You might want to clear the axes before plotting new content using plt.gca().cla().

import matplotlib.pyplot as plt

plt.ion()
for i in range(100):
    x = range(i)
    y = range(i)
    # plt.gca().cla() # optionally clear axes
    plt.plot(x, y)
    plt.title(str(i))
    plt.draw()
    plt.pause(0.1)

plt.show(block=True) # block=True lets the window stay open at the end of the animation.

Alternatively to this very simple approach, use any of the examples for animations provided in http://matplotlib.org/examples/animation/index.html

(2)

In order to get each plot in a new window, use plt.figure() and remove plt.ion(). Also only show the windows at the end:

import matplotlib.pyplot as plt

for i in range(100):
    x = range(i)
    y = range(i)
    plt.figure()
    plt.plot(x, y)
    plt.title(str(i))
    
plt.show()

Note that you might find that in both cases the first plot is empty simply because for i=0, range(i) == [] is an empty list without any points. Even for i=1 there is only one point being plotted, but of course no line can connect a single point with itself.

Solution 2:

I think the best way is to create one line plot and then update data in it. Then you will have single window and single graph that will continuously update.

import matplotlib.pyplot as plt

plt.ion()
fig = plt.figure(figsize=(16,8))
axes = fig.add_subplot(111)
data_plot=plt.plot(0,0)
line, = axes.plot([],[])
for i inrange(100):
    x = range(i)
    y = range(i)
    line.set_ydata(y)
    line.set_xdata(x)
    iflen(y)>0:
        axes.set_ylim(min(y),max(y)+1) # +1 to avoid singular transformation warning
        axes.set_xlim(min(x),max(x)+1)
    plt.title(str(i))
    plt.draw()
    plt.pause(0.1)

plt.show(block=True)

Post a Comment for "Plotting A Continuous Stream Of Data With Matplotlib"