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()


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

Twitter Linkedin YC Hacker News Reddit

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')

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)

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')

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

Disable legend

this must be AFTER the call to plot


# get current axis and disable legend

Change tick label rotation

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


# rotating labels on the xaxis
# y axis

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

# for the whole plot


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

Label points in a plot

This was inspired by a guy on stackoverflow but I can't remember. If you know please send a message.

First define a function called plot_value_labels() and call it on your axis:

def plot_value_labels(axis):
    rects = axis.patches

    # For each bar: Place a label
    for rect in rects:
        # Get X and Y placement of label from rect.
        y_value = rect.get_height()
        x_value = rect.get_x() + rect.get_width() / 2

        label = '{:.2f}'.format(y_value)

        # Vertical alignment for positive values
        va = 'bottom'

        # If value of bar is negative: Place label below bar
        if y_value < 0:
            # Invert space to place label below
            space *= -1
            # Vertically align label at top
            va = 'top'

        # Create annotation
        axis.annotate(label, (x_value, y_value), 
                      xytext=(0, 2), 
                      textcoords="offset points", 

# now the actual code
import matplotlib.pyplot as plt
import numpy as np

# generate sample data
x = np.linspace(0.0,10,10)
y = np.random.uniform(low=0,high=6,size=10)

# plot bar plot,y)

# call the function we defined

simple-label-on-bar-plots Simple labels on top of bars in a bar plot

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))

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

Add grid lines

import matplotlib.pyplot as plt
import numpy as np

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

# enable grid lines in the axis

# 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:


grid-lines-in-pyplot 0.7 is a reasonable setting for the line width

Plot histogram for values in a numpy array

View all API options: pyplot docs: pyplot.hist

import matplotlib.pyplot as plt
import numpy as np

# generate sample data following a normal distribution
values = np.random.normal(size=100)
# array([ 0.49671415, -0.1382643 ,  0.64768854,...

# see all examples in the API link
Twitter Linkedin YC Hacker News Reddit

String axis labels, bar plot

Call plt.xticks(x_values, labels):

import matplotlib.pyplot as plt
import numpy as np

# generate data
xs = [1,2,3,4,5,6,7,8,9,10,11,12]
ys = np.random.normal(loc=3.0,size=12)
labels = ['jan','feb','mar','apr','may','jun','jul','aug','sept','oct','nov','dec'],ys)

# tell pyplot which labels correspond to which x values

plot-without-explicitly-setting-labels If you don't set labels,
each label is the value itself
matplotlib-bar-plot-with-strings-for-labels Set string labels using plt.xticks(xs,labels)


Dialogue & Discussion