Matplotlib: Pyplot By Example

Last updated:
Matplotlib: Pyplot By Example
Table of Contents

WIP Alert This is a work in progress. Current information is correct but more content may be added in the future.

Pyplot or Matplotlib? What's The difference?

All examples can be found online on this notebook

Initialize sample data and imports

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0.0,100,50)
y = np.random.uniform(low=0,high=10,size=50)

Change size of Figure

After plotting, get a reference to the current figure and call set_size_inches(width,height):


# get reference to the current figure
fig = plt.gcf()

fig.set_size_inches(8,3) # not needed if matplotlib inline is enabled

set_size_inches Customized image with 8x3 inches.
(Default size is 6x4)

Save plot to file (instead of displaying it)

Use plt.savefig().

The image format is deduced from the extension ('png', 'jpg', 'svg', etc)



Multiple subplots in the same Figure

Call plt.subplots() to get a figure reference and individual Axes references (one for each subplot):

# passing 2,2 as parameters indicates that you will
# get 4 subplots (2 rows and 2 columns)
fig, axes = plt.subplots(2,2)

# just plot things on each individual axes

# optionally, add a title to this subplot only
axes[1][1].set_title('Plot 4') # not needed if matplotlib inline is enabled

pyplots-subplots Create a figure with 4 individual subplots using plt.subplots()

Set Figure Title and Font size for a Figure

Use Figure.suptitle()


# get reference to the current figure
fig = plt.gcf()

fig.suptitle('IMAGE TITLE HERE', fontsize=18) # not needed if matplotlib inline is enabled

set figure title pyplot suptitle() acceps parameters you would normally use in matplotlib.Text

Set Title and Font size for a single Axis

Similar to the above, but acts on a single Axis (useful if you have multiple suplots on the same Figure)


# get reference to the current axis
ax = plt.gca()

ax.set_title('title for this axis only', fontsize=20)

Change legend text and location

Use plt.legend() using the text and the location string (e.g. 'upper left' or 'lower right') as arguments.


# when legend is called on the global pyplot
# namespace like this, it acts on the current axes
plt.legend(['Example legend'],loc='upper center') # not needed if matplotlib inline is enabled

set legend size Function legend() is available on pyplot but also on individual
Axes instances

Change tick label rotation

Use plt.xticks() or plt.yticks and set the rotation argument (degrees)


# rotating labels on the xaxis
# y axis
plt.yticks(rotation=60) # not needed if matplotlib inline is enabled

rotate-ticks-on-pyplot You can change the label rotation for both the x-axis and the y-axis

Set Axis labels and fontsize

Use plt.xlabel() or plt.ylabel, using the same arguments that are accepted by plt.text().


plt.xlabel('time (s)',color='red',fontsize=30)
plt.ylabel('temperature (C)', fontsize=15)

axis-labels-and-fontsize You can use any other arguments from plt.text() too.

Set y-axis, x-axis limits



plt.xlim(-30,130) # not needed if matplotlib inline is enabled

y-axis-limit-and-x-axis-limit Same data as before, with more room around it.

Add text to a plot


Label points in a plot

TODO this is called annotation by mplib

Set tick frequency

Use plt.xticks with np.arange (for the y-axis, use yticks instead).

Template: plt.xticks(np.arange(<start>,<end>,<step>)).


# make the limits a bit larger so that we can see the results

# tell pyplot to write a x-axis tick every 5 units
plt.xticks(np.arange(0, 100, 5)) not needed if matplotlib inline is enabled

xticks-more-frequent X-Axis ticks are drawn every 5 units, as per the call to xticks

Add grid lines


# select both y axis and x axis
gridlines = plt.gca().get_xgridlines() + plt.gca().get_ygridlines()

# choose line width
line_width = 0.7

for line in gridlines:


Dialogue & Discussion