Matplotlib Study Note
Resources
All of the reading comes from the Tutorial page of matplotlib
. I have read the following pages:
- Usage Guide
- The Lifecycle of a Plot
- Customizing Matplotlib with style sheets and rcParams
- Artist Tutorial
- Legend Guide
- Customizing Figure Layouts Using GridSpec and Other Functions
My First Confusion
Which one should I use, matplotlib.pyplot
or figure.Figure
?
matplotlib
has two interfaces:
-
Figure
being the object-oriented interface -
pyplot
being the state-based interface.
They are equally powerful and both are illustrated in matplotlib
docmentation. But it is better to stick to the one and do no mix them. Some suggestions are:
-
pyplot
behaves like base plot in R and is suggested when generating simple plots in an interactive environment (e.g. Jupyter notebook). - In general, it is suggested to use
figure.Figure
.
I will focus on using the figure.Figure
interface throughout my study notes.
Exploration of Plotting
Some common imports are as follow:
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
I have compiled the following list of examples for generating figures. Each example provides some information on figure customization.
-
Generating a multi-line plot with a legend and axis labels
-
Generating a bar plot with customizations of the automatic layout, the figure style, the x-axis, figure saving, and combining multiple visualizations
-
An example matplotlibrc file with customization settings for all kinds of properties. Typically, we can change them by using the following code. Actually,
mpl.rcParams
is just a dictionary that controls the default aesthetics. Changing its values will change the default setting.mpl.rcParams['lines.linewidth'] = 2
mpl.rcParams.update({'font.size': 22})
mpl.rc('lines', linewidth=4, linestyle='-.')
mpl.rc('ytick.minor', size=0.33333)
ax.plot([1, 2, 3], [1, 3, 2], linewidth=4)
-
Changing properties of axis containers including ticks and labels
There are two types of Artists: primitives and containers. The primitives represent the standard graphical objects we want to paint onto our canvas (Line2D, Rectangle, Text, AxesImage, etc.), and the containers are places to put them (Tick, Axis, Axes and Figure).
-
Fine-tuning legend position using
bbox_to_anchor
andloc
Those artists with an empty string as label or with a label starting with “_” will be ignored.
-
Creating more complex legends with legend handler
-
Creating complex grid layout with
Gridspec
and adjusting margins between panels
Performance Considerations
All of the following points and more are available from the Performance section.
-
Lines: Set
rcParams['path.simplify']
andrcParams['path.simplify_threshold']
to speed up line segment redering. - Legends: Specifically provide a location for legends to avoid the expensive default operation of finding the best location.
-
Presets: Use the
fast
style for automatic simplification.