Show Menu
Cheatography

Python - Matplotlib Cheat Sheet (DRAFT) by

Matplotlib for visualization library

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

TO START

conda install matplotlib
import matplotlib.pyplot as plt

# to print graphs in notebooks
%matplotlib inline

BASICS

FUNCTIONAL METHOD
plt.pl­ot(x,y)
simple line plot
-plt.x­lab­el(­'str')
set x label
-plt.y­lab­el(­'str')
set y label
-plt.t­itl­e('­str')
set title
plt.show()
show plot
plt.su­bpl­ot(­r,c,1)*
plt.plot(x, y)
plt.su­bpl­ot(­r,c,2)
plt.plot(y, x, 'g*-')
create multiplots
OBJECT ORIENTED METHOD (more control)
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
ax.plot(x, y, 'b')
ax.set_xlabel(''str)
ax.set_ylabel('str')
ax.set_title(''str)
create canvas
create axes*
create plot
set x label
set y label
set title
** add more axis to have more figures
fig, ax = plt.su­bpl­ots­(r,c)*
axes[0].plot(x,y)
axes[1].plot(x,y)
axes[0].set_title('str')
axes[1].set_title(''str)
subplots
create pl ax1
create pl ax2
set plot 1 title
set plot 2 title
subplot() command requires to specify the number of row and column we want to print the plots, and the third parameter specify what of the graph we are going to handle.
axes: ([left, bottom, width, height])
fig, axes allow you to auto-m­anage axis, you don't have to create them. Axes, now, will be an array of axis.We could use for loop to populate labels on axis.
 

SIZE, SAVE, LEGEND

plt.ti­ght­_la­yout()
avoid overlap
plt.fi­g(f­igs­ize­=(x,x))
set figuresize
plt.fi­g(f­igs­ize­=(x,x), dpi=x)
set dpi
fig.sa­vef­ig(­"­nam­e.p­ng")
save figure
fig.sa­vef­ig(­"­nam­e", dpi=200)
..and set dpi
ax.plot(x, y, label=­"­str­")
set legend
ax.leg­end()
show legend
ax.legend(loc=0)
ax.legend(loc=1)
ax.legend(loc=2)
ax.legend(loc=3)
ax.legend(loc=4)
best
upper right
upper left
lower left
lower right
subplot() command requires to specify the number of row and column we want to print the plots, and the third parameter specify what of the graph we are going to handle.
axes: ([left, bottom, width, height])
fig, axes allow you to auto-m­anage axis, you don't have to create them. Axes, now, will be an array of axis.We could use for loop to populate labels on axis.

COLORS, LINEWI­DTHS, LINETYPES

fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
ax.plot(x,y
color='#xxxxxx',
lw=x,
alpha=x,
ls='',
marker='',
markersize=x,
markerfacecolor='',
markeredgecolor='',
markeredgewidth=x)
----
----
----
set color
set linewidth
set alpha
set linestyle
set markertype
set marker size
set mark color
set external col
set marker wdt
ax.set­_xl­im(­[0,1])
set x axes limit
ax.set­_yl­im(­[0,1])
set y axes limit
ax.plot(x, y, 'r--')
MATLAB style