Best practices for Matplotlib plots

The object-oriented Matplotlib API is slightly more verbose, but more robust than the state-machine API.

Object-oriented

from matplotlib.figure import Figure

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)

f1.savefig("example.png")

You can do virtually everything from the OO interface without the risk of updating the wrong plot as with the state machine.

state machine

The state machine method is easier, but risks updating the wrong plot, as the plot in focus is updated.

import matplotlib.pyplot as plt

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

plt.show()

Notes

  • “Effective Matplotlib” reference guide for moderately advanced Matplotlib graphs.