11- Procedural vs. Object-Oriented Plotting in Matplotlib
One of the most confusing things about learning Matplotlib is that it supports two fundamentally different ways of approaching plotting. These have been mentioned earlier, in the context of comparing programming languages: "procedural" and "object-oriented". Python is an object-oriented language, however Matlab (on which Matplotlib was based) is procedural. This means there are two different ways of draing and working with plots in Matplotlib, but trying to combine these approaches usually ends in despair.
In this lesson I discuss the differences between these approaches, how to recognize them in the wild, and give advice on which approach to use.
Summary:
- Matplotlib allows either procedural or object-oriented approaches to plotting
- It's important to be aware of this, and be able to identify which one is being used, especially when trying to using online examples in your own code
- The procedural approach typically starts with a `plt.plot()` command
- The plot is then modified by additional *functions* that start with `plt.` (such as `plt.title()` to set a title)
- The object-oriented approach starts by defining a plot object, with `plt.subplots()`, and assigning the result of this to `fig` and `ax` variables(i.e., `fig, ax = plt.subplots()`)
- The plot is then modified using *methods* that apply to axes objects, such as `ax.set_title()`
- Procedural and object-oriented approaches are incompatible with each other, so trying to combine bits of code that use the different approaches (as may happen if you have a bit of code and are using online help to improve it) usually results in errors and frustration
- Both procedural and object-oriented approaches are valid ways to use Matplotlib. In general, the object-oriented approaches are more pythonic, and they also are generally better when you want to generate a figure with different subplots
From the course, NESC 3505 Neural Data Science, by Aaron J Newman, Dalhousie University, Halifax, NS, Canada.
All course videos are here:
Textbook is available here: