Matplotlib

Graphing stuff in python

This notebook is more oriented to being a gallery of possibilities (or a set of templates) rather than a serious inductive deep-dive.


In [2]:
# Basic matplotlib import (with "magic" %matplotlib inline
# function for integration with jupyter)
%matplotlib inline
from matplotlib import pyplot as plt
import numpy as np
import pandas as pd

Simple plotting session


In [4]:
# Make up some data
x = np.arange(-5,5.5,0.5)

# Set up the plot
fig, ax = plt.subplots()

# "fig" is the whole plot we're making (including margins, overall titles, etc.)
# "ax" corresponds to a panel that we're plotting
ax.plot(x,x)
fig.savefig("save-the-fig.pdf")

# End plot session
plt.show()


Basic scatter plot


In [5]:
# Make up some data
x = np.arange(-5,5.5,0.5)

# Initialize plot
fig, ax = plt.subplots()

# Plot data
ax.plot(x,x,"o",color="blue",label="very clean fake data")
ax.plot(x,x,"-",color="red",label="a fake fit to fake data")
ax.plot((-5,5),(-2,2),"--",color="green",label="dashed line!")

# Annotate the figure
ax.set_title("this is a title")
ax.set_xlabel("x")
ax.set_ylabel("x,again")
ax.text(1,-2,"text on plot!")

# Make the plot go from -6 to 6 in both x and y, making the
# scale identical for both x and y (meaning units/pixel are
# the same in both.)
ax.set_xlim(-6,6)
ax.set_ylim(-6,6)
ax.set_aspect('equal', 'box')

# add a legend
ax.legend(frameon=False,title="legends can have titles")

fig.savefig("this-will-be-a-pdf-file.pdf")

# End plot session
plt.show()


Scatter plot with error bars, different styling


In [ ]:
# Make up some data
x = np.arange(-5,5.5,0.5)
y = x + np.random.normal(0,0.5,len(x))
x_err = np.random.normal(0,0.7,len(x))
y_err = np.random.normal(0,0.7,len(x))

# Initialize plot
fig, ax = plt.subplots()

# Plot, with error bars
ax.errorbar(x,y,xerr=x_err,yerr=y_err,fmt="o",color="black",label="raw data")
ax.plot([-6,6],[-6,6],"--",color="gray",label="1:1 line")

ax.set_title("you really should have a title")
ax.set_xlabel("x, some units")
ax.set_ylabel("y, some other units")

# Make the plot go from -6 to 6 in both x and y, making the
# scale identical for both x and y (meaning units/pixel are
# the same in both.)
ax.set_xlim(-6,6)
ax.set_ylim(-6,6)
ax.set_aspect('equal', 'box')

# add a legend
ax.legend(loc="lower right", title="legends have boxes by default")

fig.savefig("this-will-be-a-png-file.png")

# End plot session
plt.show()

Plot with log scale


In [ ]:
# Make up some data
x = np.arange(-5,5.5,0.5)
y = np.exp(x + np.random.normal(0,0.5,len(x)))
x_err = np.random.normal(0,0.7,len(x))
y_err = np.random.normal(0,0.7,len(x))

# Initialize plot
fig, ax = plt.subplots()

# Plot, with error bars
ax.errorbar(x,y,xerr=x_err,yerr=y_err,fmt="o",color="black",label="raw data")
ax.plot(x,np.exp(x),"--",color="green",label="exp looks linear on log scale")

# Let's give it a log y-scale
ax.set_yscale("log")

ax.set_title("logs!")
ax.set_xlabel("x, some units")
ax.set_ylabel("y (on a log scale!)")

# Make the plot go from -6 to 6 in both x and y, making the
# scale identical for both x and y (meaning units/pixel are
# the same in both.)
ax.set_xlim(-6,6)
ax.set_ylim(0.0001,1000)

# add a legend
ax.legend(frameon=False)

fig.savefig("this-will-be-an-svg.svg")

# End plot session
plt.show()

Customizing axes, changing figure size


In [9]:
# Make up some data
x = np.arange(-5,5.5,0.5)
y = x + np.random.normal(0,0.5,len(x))

# Initialize plot
fig, ax = plt.subplots(figsize=(10,3))

# Plot, with error bars
ax.plot(x,y,"o",color="black",label="raw data")

ax.set_xlabel("check out these messed up x ticks")
ax.set_xticks([-3,0.1,6])
ax.set_xticklabels(["A","B","C"])

# Make the plot go from -6 to 6 in both x and y, making the
# scale identical for both x and y (meaning units/pixel are
# the same in both.)
ax.set_xlim(-6,6)
ax.set_ylim(-6,6)

# End plot session
plt.show()


Barplot!


In [10]:
import string

# Make up some data
x = np.arange(-5,6,1)
y = x + np.random.normal(0,0.5,len(x))
x_err = np.random.normal(0,0.7,len(x))
y_err = np.random.normal(0,0.7,len(x))


# Initialize plot
fig, ax = plt.subplots()

ax.bar(x,y,yerr=y_err,color="gray",edgecolor="black")
ax.set_xticks(x)
ax.set_xticklabels(string.ascii_letters[:len(x)])

ax.set_xlabel("treatment")
ax.set_ylabel("output")

ax.set_xlim(-6,6)
ax.set_ylim(-6,6)

# End plot session
plt.show()


Plot with multiple panels


In [56]:
import string

# Make up some data
x = np.arange(-5,6,1)
y = x + np.random.normal(0,0.5,len(x))
x_err = np.random.normal(0,0.7,len(x))
y_err = np.random.normal(0,0.7,len(x))

# Initialize plot, forcing linking the x-axes across columns
fig, ax = plt.subplots(2,3,sharex="col",constrained_layout=True)

# ax is an 2x3 array, following row,column convention. Panels
# can be accessed by coordinates from top-left to bottom-right
ax[0,0].plot(x,y,"o",color="black")
ax[1,0].errorbar(x,y,xerr=x_err,yerr=y_err,fmt="o",color="orange")

ax[0,1].plot(x,y,"o",color="blue")
ax[1,1].plot(x,-y,"o",color="green")

ax[0,2].bar(x,y)
ax[1,2].bar(x,y,edgecolor="pink",color="gray")

# Set the x and y limits for the top-left.  This will fix x for the
# column
ax[0,0].set_xlim(-6,6)
ax[0,0].set_ylim(-6,6)

# You can set x limits for each column; y limits for each panel
ax[0,1].set_xlim(-9,9)
ax[0,1].set_ylim(-9,9)
ax[1,1].set_ylim(-6,6)

# Set x-ticks on a single column
ax[0,0].set_xticks(np.arange(-5,7,2))

# You can label axes for each panel
ax[1,0].set_xlabel("x")
ax[1,1].set_xlabel("x")
ax[1,2].set_xlabel("x")
ax[0,0].set_ylabel("y")
ax[1,0].set_ylabel("y")

# Give individual panels lables
ax[0,0].set_title("top middle")
ax[1,0].set_title("bottom left")

fig.suptitle("MASTER TITLE",fontsize=16)

# End plot session
plt.show()


Global customization of fonts, sizes and styling


In [ ]:
# Global parameters you can set on all plots.  
# If you run this, it will affect all plots in the notebook 

SMALL_SIZE = 8
MEDIUM_SIZE = 10
BIGGER_SIZE = 26

plt.rc('font', size=SMALL_SIZE)          # controls default text sizes
plt.rc('font', family="Times New Roman")           # change font!!
plt.rc('axes', titlesize=SMALL_SIZE)     # fontsize of the axes title
plt.rc('axes', labelsize=MEDIUM_SIZE)    # fontsize of the x and y labels
plt.rc('xtick', labelsize=SMALL_SIZE)    # fontsize of the tick labels
plt.rc('ytick', labelsize=SMALL_SIZE)    # fontsize of the tick labels
plt.rc('legend', fontsize=SMALL_SIZE)    # legend fontsize
plt.rc('figure', titlesize=BIGGER_SIZE)  # fontsize of the figure title

# Apply master styling
plt.style.use('ggplot')

In [57]:
point_types = [".",",","o","v","^","<",">","1","2","3","4","8",
               "s","p","P","*","h","H","+","x","X","D","d","|",
               "_"]
for i in range(len(point_types)):
    plt.plot([2*i,2*i+4],[2*i,2*i],point_types[i],color="black")

plt.show()

line_types = ["-","--",":"]
for i in range(len(line_types)):
    plt.plot(x,5*i+x**2,line_types[i])



In [58]:
# blue, green, red, cyan, magenta, yellow, black, white
colors = ["b","g","r","c","m","y","k","w"]

for i in range(len(colors)):
    plt.plot([2*i,2*i+4],[2*i,2*i],"o",color=colors[i])



In [ ]: