Dynamic plotting with matplotlib

share on google plus share on facebook share on twitter share on linkedin share via email

Matplotlib is a great tool to visualise two-dimensional geometric data (and 3D data to some extent). You can also use it to dynamically visualise the convergence of an iterative solver.

Surprisingly, you don’t need any fancy functionality to accomplish this, such as, for example, the FuncAnimation object of the animation package.

import matplotlib.pyplot as plt
import time
import random

ysample = random.sample(xrange(-50, 50), 100)

xdata = []
ydata = []

plt.show()

axes = plt.gca()
axes.set_xlim(0, 100)
axes.set_ylim(-50, +50)
line, = axes.plot(xdata, ydata, 'r-')

for i in range(100):
    xdata.append(i)
    ydata.append(ysample[i])
    line.set_xdata(xdata)
    line.set_ydata(ydata)
    plt.draw()
    plt.pause(1e-17)
    time.sleep(0.1)

# add this if you don't want the window to disappear at the end 
plt.show()

One Response to “Dynamic plotting with matplotlib”

  1. Aditya says:

    import matplotlib.pyplot as plt

    plt.ion()

    for i in range(10):
    plt.scatter(i, i)
    plt.pause(0.5)

    this also works but only for scatter()

Leave a response

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>