Show Menu
Cheatography

matplotlib.pyplot Cheat Sheet by

Basic and intermediate matplotlib.pyplot functions

Importing the library

import matplotlib.pyplot as plt

Plots and key arguments

Line graph
plt.plot()
(x_data, y_data)
Scatter plot
plt.sc­atter()
(x_data, y_data)
Bar chart
plt.bar()
(x_locs, bar_he­ights, width = int)
Histogram
plt.hist()
(data, bins = int)
Pie chart
plt.pie()
(data, labels = list)

Optional arguments

color ="co­lor­"
Change plot color
marker = "­sym­bol­"
Change marker for line or scatter plot (".", "­x", "­|", "­o")
markersize = int
Change marker size
linewidth = int
Change line width for line graph
cmap = colormap
Color plot according to a colormap
 

Key functions

plt.clf()
Clear figure
plt.sa­vef­ig(­"­fil­ena­me")
Save figure (call before plt.sh­ow())
plt.show()
Show figure

Axis functions

plt.xl­im(­xmin, xmax)
Set the limits for the x axis
plt.yl­im(­ymin, ymax)
Set the limits for the y axis
plt.xs­cal­e("scale type")
Set scale for the x axis (ex. "­log­")
plt.ys­cal­e("scale type")
Set scale for the y axis (ex. "­log­")
plt.tw­inx()
Add a second y axis
plt.ax­is(­"­off­")
Do not show the axes
plt.gc­a().in­vert_ xaxis()
Invert the x axis
plt.gc­a().in­vert_ yaxis()
Invert the y axis
 

Labeling functions

plt.ti­tle­("ti­tle­")
Add a title
plt.xl­abe­l("x axis label")
Add a label to the x axis
plt.yl­abe­l("y axis label")
Add a label to the y axis
plt.le­gen­d(loc = int)
Add a legend
plt.xt­ick­s(r­ang­e(min, max, interval)
Modify the x axis tick marks

Multiple plots

plt.plot(x_data1, y_data1)
plt.plot(x_data2, y_data2)
plt.plot(x_data3, y_data3)

plt.show()
You can put multiple plots in one figure by defining each one before plt.show() or plt.sa­vefig()

Using colormaps

# Choose a colormap and assign to a variable
cm = plt.cm.get_cmap("RdYlBu")

# Set the color map in a plot
plt.scatter(x_data, y_data, cmap=cm)
 

Comments

Great job! I'm just learning Python. Your cheat sheet is useful to me.

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.

          Related Cheat Sheets

            Python 3 Cheat Sheet by Finxter

          More Cheat Sheets by gabriellerab