OO vs. pyplot#
If you start exploring matplotlib documentation or other internet resources/tutorials, you will likely run into matplotlib syntax that is different than what’s presented here. That is because Matplotlib has two interfaces.
The first is an
object-oriented (OO) interface. When working in theOOinterface, we utilize an instance ofaxes.Axesto render visualizations on an instance offigure.Figure.The second is based on
MATLABand uses a state-based interface. This second interface is encapsulated in thepyplotmodule.pyplotis a collection of functions that make matplotlib work likeMATLAB.
At first glance, pyplot can seem like a much easier alternative to the object-oriented interface.
import matplotlib.pyplot as plt # import statement
plt.plot([1,2,3,4]) # create plot
plt.ylabel('some numbers') # add label
plt.show() # show output
No figure, no axis- what magic! Except…pyplot doesn’t scale with multiple plots or plots that require significant customization. The pyplot interface hs much less flexible than the OO interface. Plus, matplotlib’s own documentation recommends that you use the OO interface.
Additional Resources#
For more on the differences between these two interfaces and how to translate sample code across interfaces:
Tejas Sanap, “Pyplot vs Object Oriented Interface” matplotblog (27 May 2020)