Understanding the Structure of Matplotlib | by Soner Yıldırım | Towards Data Science

Matplotlib is a widely used python data visualization library. It provides many different kinds of 2D and 3D plots that are very useful for data analysis and machine learning tasks.
Matplotlib offers flexibility. There are multiple ways to create plots. In order to master matplotlib, it is necessary to have a thorough understanding of its structure.
Matplotlib consists of three main layers.
If you’re not a develepor, you’re not likely to use or deal with the backend layer. It has three abstract classes:
FigureCanvas: Defines the area on which the figure is drawn.
Renderer: It is the tool to draw on FigureCanvas.
Event: Handles user inputs such as keybord strokes and mouse clicks.
It is similar to how we do drawing on paper. Consider you want to draw a painting. You get a blank paper (FigureCanvas) and a brush (Renderer). You ask your friend what to draw (Event).
Artist layer is composed of one object which is Artist.
Everything that we see on a plot produced by matplotlib is an Artist instance.
Titles, lines, texts, axis labels are all instances of Artist. Figure is the main Artist object that holds everything together. Let’s create a Figure:
#importing matplotlibimport matplotlib.pyplot as plt%matplotlib inline#creating a figure artistfig = plt.figure(figsize=(10,6))<Figure size 720x432 with 0 Axes>
We have created a figure but it does not have anything to show. Think of it as a container that hold the components of a plot together.
There are two types of artist objects:
Composite: Figure, Axes
Primitive: Line, Circle, Text
We need to add one or more Axes to Figure to be able to create an actual plot. Let’s see it on the action.
fig = plt.figure(figsize=(10,6))ax = fig.add_subplot(111)
We have added an Axes to the Figure we created earlier. We now have kind of an empty plot:
Please note that we have used the scripting layer to produce these plots. I just wanted to show the idea of Artist objects.
Note: We have used object-oriented style where we explicitly define instances of Artist objects. The other option is called pyplot style where we let pyplot to create figure and axes objects.
We will stick to the object-oriented style throughout this post.
This is the layer where we are most likely to deal with. Scripting layer is the matplotlib.pyplot interface. Thus, when we create plots using “plt” after the following command, scripting layer is what we play with.
import matplotlib.pyplot as plt
Scripting layer automates the process of putting everthing together. Thus, it is easier to use than the Artist layer.
Let’s create some plots that actually look like a plot.
#create array to be plottedimport numpy as npser = np.random.randn(50)#create the plotfig = plt.figure(figsize=(10,6))ax = fig.add_subplot(111)ax.plot(ser)
We have created a Figure and Axes. Then called plot function on the Axes object and pass the array to be plotted. The rendered plot is:
This figure has 1 Axes but a figure can contain multiple Axes. Let’s create one with multiple Axes:
#arrays to be plottedser1 = np.random.randn(50)ser2 = ser1**2#create figure and axesfig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2,                  sharey=True,figsize=(10,6))#plot the arrays on axesax1.plot(ser1)ax2.plot(ser2)
We created the figure and axes (ax1 and ax2) with one line of code using subplots function.
Matplotlib offers a highly flexible working environment. We have full control over the plots we created. Recall that everything we see on a matplotlib figure is an instance of Artist. Let’s add different types of Artists to the plot above.
ser1 = np.random.randn(50)ser2 = ser1**2fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2,                  sharey=True, figsize=(12,6))ax1.plot(ser1)ax1.grid()ax1.set_title('First Series', fontsize=15)ax1.set_ylabel('Values', fontsize=12)ax1.set_xlabel('Timesteps', fontsize=12)ax2.plot(ser2)ax2.set_title('Second Series', fontsize=15)ax2.text(25,-1, 'First Series Squared', fontsize=12)ax2.set_xlabel('Timesteps', fontsize=12)
In addition to the titles and axis labels, we have added grid lines to the first axes and a text artist to the second axes. The plot we have produced:
There is so much more we can do with matplotlib. As with any other tool, it requires lots of practice to master. However, a concrete and fundamental first step is to learn the basics and the structure. After that, we can create more advanced plots by practicing.
Thank you for reading. Please let me know if you have any feedback.