Show Menu
Cheatography

python plotting Cheat Sheet (DRAFT) by

This is a draft cheat sheet. It is a work in progress and is not finished yet.

Import

import matplotlib.pyplot as plt
import seaborn as sns

Plotting Process

0. Get data
1. Control Figure Aesthetics
2. Plot
3. Customise

Figure Aesthetics

f, ax = plt.subplots(figsize=(5, 6))
sns.set() # reset defaults
sns.set_style("whitegrid") # white background (not grey)
sns.set_palette("pastel") # change colours

Axis Grids

# histogram of age by survived (0,1) and sex (m,f) = 4 plots
g = sns.FacetGrid(titanic, col="survived", row="sex") 
g = g.map(plt.hist, "age")
plt.show(g)

# plot survived by pclass - two lines by sex (hue)
sns.factorplot(x="pclass", y="survived", hue="sex", data=titanic)

# regplot - use hue to split by species
sns.lmplot(x="sepal_width", y="sepal_length", hue="species", data=iris)

# pair-wise distributions and histograms
sns.pairplot(iris)
# alternate - create pair grid and then map scatter plots
h=sns.PairGrid(iris)
h=h.map(plt.scatter)

# customise
g.set(xlim=(0,5), ylim=(0,5), xticks=[0, 2.5, 5], yticks=[0, 2.5, 5])
g.set_ylabels("yaxis") / g.set_axis_labels("Y", "X")
 

Plots

# scatter plot
sns.stripplot(x="species", y="petal_length", data=iris)
sns.swarmplot(x="species", y="petal_length", data=iris) # no overlap

# bar chart
sns.barplot(x="sex", y="survived", hue="class", data=titanic)

# count plot (similar to histogram for categorical)
sns.countplot(x="deck", data=titanic, palette="Greens_d")

# point plot (like line chart?)
sns.pointplot(x="class", y="survived", hue="sex", data=titanic,
                     palette={"male":"g", "female":"m"},
                     markers=["^", "o"],
                     linestyles=["-", "--"])

# box plot
sns.boxplot(x="alive", y="age", hue="adult_male", data=titanic)

# histogram
sns.distplot(data.colname, kde=False, color="b")

# heat map
sns.heatmap(uniform_data, vmin=0, vmax=1)

# customise
pltobj.set(xlabel="x", title="title", ylabel="y", xlim=(0,100), ylim=(0,100))
pltobj.title("A title") # similar to above if only want one item

Other

plt.show()
plt.savefig('foo.png')
plt.close() # close window
plt.cla() / plt.clf() # close axis / figure