Best practices for Matplotlib plots

Related: Date/time in Matplotlib


The best way to use Matplotlib is to use the “object oriented” interface. Here’s an example:

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.figure()
plt.plot(x,y)
plt.title('my figure')
plt.xlabel('x [in]')
...

plt.show()

References

Useful reference guide for moderately advanced Matplotlib graphs

Tags:

Categories:

Written by Michael Hirsch, Ph.D. //

Comments