Matplotlib Cheat Sheet
Matplotlib Cheat Sheet
Matplotlib Cheat Sheet
Preliminaries
Version 3 May 2015 - [Draft Mark Graph mark dot the dot graph at gmail dot com @Mark_Graph on twitter]
1!
!
Line plots using ax.plot() Scatter plots using ax.scatter()
Single plot constructed with Figure and Axes A simple scatter plot
# --- get the data x = np.random.randn(100)
x = np.linspace(0, 16, 800) y = x + np.random.randn(100) + 10
y = np.sin(x) fig, ax = plt.subplots(figsize=(8, 3))
# --- get an empty figure and add an Axes ax.scatter(x, y, alpha=0.5, color='orchid')
fig = plt.figure(figsize=(8,4)) fig.suptitle('Example Scatter Plot')
ax = fig.add_subplot(1,1,1) # row-col-num fig.tight_layout(pad=2);
# --- line plot data on the Axes ax.grid(True)
ax.plot(x, y, 'b-', linewidth=2, fig.savefig('filename1.png', dpi=125)
label=r'$y=\sin(x)$')
# --- add title, labels and legend, etc.
ax.set_ylabel(r'$y$', fontsize=16);
ax.set_xlabel(r'$x$', fontsize=16)
ax.legend(loc='best')
ax.grid(True)
fig.suptitle('The Sine Wave')
fig.tight_layout(pad=1)
fig.savefig('filename.png', dpi=125)
Version 3 May 2015 - [Draft Mark Graph mark dot the dot graph at gmail dot com @Mark_Graph on twitter]
2!
!
Add confidence bands for the regression line Changing the marker size and colour
y_hat = fitted.predict(x) N = 100
y_err = y - y_hat x = np.random.rand(N)
mean_x = x.T[1].mean() y = np.random.rand(N)
n = len(x) size = ((np.random.rand(N) + 1) * 8) ** 2
dof = n - fitted.df_model - 1 colours = np.random.rand(N)
from scipy import stats fig, ax = plt.subplots(figsize=(8,4))
t = stats.t.ppf(1-0.025, df=dof) # 2-tail l = ax.scatter(x, y, s=size, c=colours)
s_err = np.sum(np.power(y_err, 2)) fig.colorbar(l)
conf = t * np.sqrt((s_err/(n-2))*(1.0/n + ax.set_xlim((-0.05, 1.05))
(np.power((x_pred-mean_x),2) / ax.set_ylim((-0.05, 1.05))
((np.sum(np.power(x_pred,2))) - fig.suptitle('Dramatic Scatter Plot')
n*(np.power(mean_x,2)))))) fig.tight_layout(pad=2);
upper = y_pred + abs(conf) ax.grid(True)
lower = y_pred - abs(conf) fig.savefig('filename.png', dpi=125)
ax.fill_between(x_pred, lower, upper, Note: matplotlib has a huge range of colour maps in
color='#888888', alpha=0.3) addition to the default used here.
fig.savefig('filename3.png', dpi=125)
Version 3 May 2015 - [Draft Mark Graph mark dot the dot graph at gmail dot com @Mark_Graph on twitter]
3!
!
Bar plots using ax.bar() and ax.barh()
Version 3 May 2015 - [Draft Mark Graph mark dot the dot graph at gmail dot com @Mark_Graph on twitter]
4!
!
Pie Chart using ax.pie()
Plot spines
As nice as pie
# --- get some data Hiding the top and right spines
data = np.array([5,3,4,6])
x = np.linspace(-np.pi, np.pi, 800)
labels = ['bats', 'cats', 'gnats', 'rats']
y = np.sin(x)
explode = (0, 0.1, 0, 0) # explode cats
fig, ax = plt.subplots(figsize=(8, 4))
colrs=['khaki', 'goldenrod', 'tan', 'wheat']
ax.plot(x, y, label='Sine', color='red')
# --- the plot
ax.set_axis_bgcolor('#e5e5e5')
fig, ax = plt.subplots(figsize=(8, 3.5))
ax.spines['right'].set_color('none')
ax.pie(data, explode=explode,
ax.spines['top'].set_color('none')
labels=labels, autopct='%1.1f%%',
ax.spines['left'].set_position(
startangle=270, colors=colrs)
('outward',10))
ax.axis('equal') # keep it a circle
ax.spines['bottom'].set_position(
# --- tidy-up and save
('outward',10))
fig.suptitle("Delicious Pie Ingredients")
ax.xaxis.set_ticks_position('bottom')
fig.savefig('filename.png', dpi=125)
ax.yaxis.set_ticks_position('left')
# do the ax.grid() after setting ticks
ax.grid(b=True, which='both',
color='white', linestyle='-',
linewidth=1.5)
ax.set_axisbelow(True)
ax.legend(loc='best', frameon=False)
fig.savefig('filename.png', dpi=125)
Polar coordinates
# --- theta
theta = np.linspace(-np.pi, np.pi, 800)
# --- get us a Figure
fig = plt.figure(figsize=(8,4)) Spines in the middle
# --- left hand plot x = np.linspace(-np.pi, np.pi, 800)
ax = fig.add_subplot(1,2,1, polar=True) y = np.sin(x)
r = 3 + np.cos(5*theta) fig, ax = plt.subplots(figsize=(8, 4))
ax.plot(theta, r) ax.plot(x, y, label='Sine')
ax.set_yticks([1,2,3,4]) ax.spines['right'].set_color('none')
# --- right hand plot ax.spines['top'].set_color('none')
ax = fig.add_subplot(1,2,2, polar=True) ax.xaxis.set_ticks_position('bottom')
r = (np.sin(theta)) - (np.cos(10*theta)) ax.spines['bottom'].set_position((
ax.plot(theta, r, color='green') 'data',0))
ax.set_yticks([1,2]) ax.yaxis.set_ticks_position('left')
# --- title, explanatory text and save ax.spines['left'].set_position((
fig.suptitle('Polar Coordinates') 'data',0))
fig.text(x=0.24, y=0.05, ax.grid(b=True, which='both',
s=r'$r = 3 + \cos(5 \theta)$') color='#888888', linestyle='-',
fig.text(x=0.64, y=0.05, linewidth=0.5)
s=r'$r = \sin(\theta) - \cos(10' + fig.suptitle('Sine')
r'\theta)$') fig.savefig('filename.png', dpi=125)
fig.savefig('filename.png', dpi=125)
Version 3 May 2015 - [Draft Mark Graph mark dot the dot graph at gmail dot com @Mark_Graph on twitter]
5!
!
Legend to the right of the plot
N = 5
x = np.arange(N)
fig, ax = plt.subplots(figsize=(8, 3))
for j in range(5):
ax.plot(x, x*(j+1),
label='Line '+str(j))
ax.legend(loc='upper left')
fig.savefig('filename.png', dpi=125) Legend below the plot
N = 5
x = np.arange(N)
fig, ax = plt.subplots(figsize=(8, 3))
for j in range(5):
ax.plot(x, x*(j+1),
label='Line '+str(j))
box = ax.get_position()
ax.set_position([box.x0,
box.y0 + box.height * 0.15,
box.width, box.height * 0.85])
ax.legend(bbox_to_anchor=(0.5, -0.075),
Legend slightly outside of the plot loc='upper center', ncol=N)
N = 5 fig.savefig('filename.png', dpi=125)
x = np.arange(N)
fig, ax = plt.subplots(figsize=(8, 3))
for j in range(5):
ax.plot(x, x*(j+1),
label='Line '+str(j))
ax.legend(bbox_to_anchor=(1.1, 1.05))
fig.savefig('filename.png', dpi=125)
Version 3 May 2015 - [Draft Mark Graph mark dot the dot graph at gmail dot com @Mark_Graph on twitter]
6!
!
Using GridSpec layouts (like list slicing)
Multiple plots on a canvas import matplotlib.gridspec as gs
gs = gs.GridSpec(3, 3) # nrows, ncols
Using Axes to place a plot within a plot fig = plt.figure(figsize=(8,4))
fig.text(x=0.01, y=0.01, s='Figure',
fig = plt.figure(figsize=(8,4)) color='#888888', ha='left',
fig.text(x=0.01, y=0.01, s='Figure', va='bottom', fontsize=20)
color='#888888', ha='left', ax1 = fig.add_subplot(gs[0, :]) # row,col
va='bottom', fontsize=20) ax1.text(x=0.2,y=0.2,s='0, :', color='b')
# --- Main Axes ax2 = fig.add_subplot(gs[1,:-1])
ax = fig.add_axes([0.1,0.1,0.8,0.8]) ax2.text(x=0.2,y=0.2,s='1, :-1', color='b')
ax.text(x=0.01, y=0.01, s='Main Axes', ax3 = fig.add_subplot(gs[1:, -1])
color='red', ha='left', va='bottom', ax3.text(x=0.2,y=0.2, s='1:, -1', color='b')
fontsize=20) ax4 = fig.add_subplot(gs[-1,0])
ax.set_xticks([]); ax.set_yticks([]) ax4.text(x=0.2,y=0.2, s='-1, :0', color='b')
# --- Insert Axes ax5 = fig.add_subplot(gs[-1,-2])
ax= fig.add_axes([0.15,0.65,0.2,0.2]) ax5.text(x=0.2,y=0.2, s='-1,:-2', color='b')
ax.text(x=0.01, y=0.01, s='Insert Axes', for a in fig.get_axes():
color='blue', ha='left', va='bottom', a.set_xticks([])
fontsize=20) a.set_yticks([])
ax.set_xticks([]); ax.set_yticks([])
fig.suptitle('An Axes within an Axes') fig.suptitle('GridSpec Layout')
fig.savefig('filename.png', dpi=125) fig.savefig('filename.png', dpi=125)
Version 3 May 2015 - [Draft Mark Graph mark dot the dot graph at gmail dot com @Mark_Graph on twitter]
7!
!
Cautionary notes
Version 3 May 2015 - [Draft Mark Graph mark dot the dot graph at gmail dot com @Mark_Graph on twitter]
8!
!