Best practices for Matplotlib plots

Use OO, not state-machine Matplotlib

The preferable way to create Matplotlib figures that you can manipulate, update, and save easily is:

from matplotlib.pyplot import figure,show

f1 = figure()
a1 = f1().gca()
p1 = a1.plot(x,y)
a1.set_title('my plot')
a1.set_xlabel('x [in]')
a1.set_ylabel('y [out]')

#... (more plots)

show() # program waits here for figure to close or program to end.

You can do virtually everything from the OO interface without the risk of updating the wrong plot as with the state machine. Write a comment if you’d like more examples.

DON’T use matplotlib state machine

Don’t use the state machine method. It doesn’t save any time and can lead to updating the wrong plot.

# don't do the following
import matplotlib.pyplot as plt

plt.title('my figure')
plt.xlabel('x [in]')


Useful reference guide to moderately advanced Matplotlib graphs

Leave a Comment