Matplotlib cheatsheet
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
# keyword arguments: color, linestyle
plt.plot(x, np.sin(x), label="sin(x)")
plt.plot(x, np.cos(x), label="cos(x)")
plt.show()
Axis limits
plt.xlim(low, high)
plt.ylim(low, high)
# equivalent:
plt.axis([xlow, xhigh, ylow, yhigh])
# fit to graph
plt.axis("tight")
# equal aspect ratio
plt.axis("equal")
Labels
plt.title("...")
plt.xlabel("...")
plt.ylabel("...")
# create a legend
plt.legend()
Scatterplots
plt.plot(x, y, 'o')
# equivalent:
plt.scatter(x, y, marker='o')
# connect points with line
plt.plot(x, y, '-o')
# set colors and sizes
plt.scatter(x, y, c=colors, s=sizes, alpha=0.3)
plt.colorbar()
plt.scatter
is more powerful but less efficient than plt.plot
.
Error bars
plt.errorbar(x, y, yerr=dy)
Histograms
plt.hist(data, bins=30)
# histtype='stepfilled' and alpha=0.3 good for plotting
# multiple histograms on top of each other
Side-by-side plots
# (rows, cols, index)
plt.subplot(1, 2, 1)
plt.plot(...)
plt.subplot(1, 2, 2)
plt.plot(...)
plt.show()
Set a stylesheet
with plt.style.context('classic'):
...
Seaborn
More convenient interface and more stylish graphics:
import seaborn as sns
sns.set()
iris = sns.load_dataset("iris")
sns.pairplot(iris, hue="species", size=1.5)
Links
- Python for Data Science book – chapter 4 covers Matplotlib
- Ten Simple Rules for Better Figures