Data Visualization for absolute beginners[part 2/3]
Matplotlib Object-Oriented Method
Now that we’ve covered the basics, let’s shift our focus to introduction of Matplotlib’s Object Oriented API. This will allow us to instantiate figure objects and then we can call methods from that object.
Introduction to the Object-Oriented Method
The idea here is to use a more formal Object-Oriented method to create figure objects and then call the respective methods or attributes of that object. This proves to be a wonderful practice when dealing with multiple plots.
We will now begin by creating a figure instance. Then we will add axes to that figure.
# Object oriented method
# Create Figure (empty canvas)
fig = plt.figure()# Add set of axes to figure
axes = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # left, bottom, width, height (range 0 to 1)# Plot on that set of axes
axes.plot(x, y, 'b')
NOTE : We did the same thing using plt.plot(x,y) in part 1 of this tutorial. But now using this Object-Oriented approach we are going to have a lot more control over our fig object and we can easily add more than one axes to our figure as shown below.
# Creates blank canvas
fig = plt.figure()axes1 = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # main axes
axes2 = fig.add_axes([0.2, 0.5, 0.4, 0.3]) # inset axes# Larger Figure Axes 1
axes1.plot(x, y, 'b')# Insert Figure Axes 2
axes2.plot(y, x, 'r')
Subplots()
Now we are going to learn how to create subplots using the same object-oriented approach. Subplot is different because we can specify the number of rows and columns.
The plt.subplots() object acts as a more automatic axis manager.
Basic use cases:
# Use tuple unpacking to grab fig and axes
fig, axes = plt.subplots()# Use axes object to add stuff to the plot
axes.plot(x, y, 'r')
Now we will specify the number of rows and columns while instantiating the subplots() object:
# Make an empty canvas of 1 by 2 subplots
fig, axes = plt.subplots(nrows=1, ncols=2)
# Axes is an array of axes to plot on
axes
Out[]
array([<matplotlib.axes._subplots.AxesSubplot object at 0x111f0f8d0>,<matplotlib.axes._subplots.AxesSubplot object at 0x1121f5588>], dtype=object)
Recall that in part 1 we did the same thing by manually giving rows and columns, but since its an array we can actually iterate over it and directly plot the data.
for ax in axes:
ax.plot(x, y, 'b')# Display the figure object
fig
In matplotlib, the location of axes (including subplots) are specified in normalized figure coordinates. It can happen that your axis labels or titles (or sometimes even ticklabels) go outside the figure area, and are thus clipped.
To solve this problem we can use fig.tight_layout() or plt.tight_layout() method, which on its own adjusts the positions of the axes on the figure canvas to avoid overlapping content:
tight_layout() can take keyword arguments of pad, w_pad, and h_pad. These control the extra padding around the figure border and between subplots. The pads are specified in fraction of font size.
plt.tight_layout(pad=0.4, w_pad=0.5, h_pad=1.0)
Figure size, aspect ratio, and DPI
Matplotlib allows the aspect ratio, DPI (dots per inch), and figure size to be specified when the Figure object is created. We can use the figsize
and dpi
keyword arguments.
figsize
is a tuple of the width and height of the figure in inchesdpi
is the dots-per-inch (pixels per inch).
fig = plt.figure(figsize=(8,4), dpi=100)
Out []:
<matplotlib.figure.Figure at 0x11228ea58>
These same arguments can also be passed tosubplots
function:
fig, axes = plt.subplots(figsize=(12,3)) # 12 by 4 inchesaxes.plot(x, y, 'r')
Saving figures
Matplotlib generates high-quality of output in the following format JPG, PNG, EPS, SVG, PDF, and PGF.
In order to save a file, we will use the savefig
method in the Figure class:
fig.savefig("filename.jpg")
We can also optionally specify dots per inch (DPI) and choose different output formats
fig.savefig("filename.png", dpi=200)
Congratulations! on completing part 2 of the series head on to part 3 by clicking here
Sources
- https://www.udemy.com/course/python-for-data-science-and-machine-learning-bootcamp/
- https://sites.google.com/site/ownscratchpad/datascience/matplotlib
- https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.axes.Axes.set_xlabel.html
- https://www.southampton.ac.uk/~fangohr/training/python/notebooks/Matplotlib.html
- https://www.google.com/search?q=%22axes%20=%20fig.add_axes(%5B0.1,%200.1,%200.8,%200.8%5D)%20#%20left,%20bottom,%20width,%20height%20(range%200%20to%201)%22