Show Menu
Cheatography

MatPLotLib Cheat Sheet (DRAFT) by [deleted]

Cheatsheet for the matplotlib library.

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

Import

import matplo­tli­b.p­yplot as plt

Anatomy of a figure

Main principle

# Example
fig, ax = plt.su­bpl­ots() # Create one subplot
ax.plo­t(x1, y1) # each ax represents one plot on the figure object
ax.plo­t(x2, y2) # another plot is added to the figure object (with another color)
plt.show()

Cutomizing data appearance

ax.plo­t(x,y, marker = "­")
# indicate each data point on the line
ax.plo­t(x,y, linestyle = "­")
# change linestyle
ax.plo­t(x,y, color = "­")
# change color
ax.set­_xl­abe­l("")
# name the x axis
ax.set­_yl­abe­l("")
# name the y axis
ax.set­_ti­tle­("")
# give figure a title
ax.tic­k_p­ara­ms(­"­x"/"y­", colors = "­")
# change the color of the ticks
ax.set­_xt­ick­s(l­ist())
# change the tick values of the X axis
Use list compre­hension
ax.set­_yt­ick­s(l­ist())
# change the tick values of the y axis
Use list compre­hension

scatte­rplot

fig, ax = plt.scatter(x, y, s=area, c=colors, alpha=0.5)
ax.plot(x, y, linestyle = "None")
plt.show()

Subplot

Create the subplots
fig, ax = plt.su­bpl­ots(3, 2)
First Subplot
ax[0, 0].plot(x, y, color = "­gre­en")
Second Subplot
ax[0, 1].plot(x, y, color = "­blu­e")

Subplot

fig, ax = plt.su­bpl­ots­(rows, columns, index_­of_­sub­plot)
fig = container holding one to more axes; ax = individual plot
ax.plo­t([x], y, color = "­gre­en")
[X] = X coordi­nates; Y = Y coordi­nates
plt.show()
Plot the figure.
plt.su­bpl­ots­(rows, columns, sharey = True)
All subplots have same range of Y-axis values

Time series

Once there is column with a DateTime datatype then matplotlib will recognize that this is a variable that represents time.

Time series

Plot time series
ax.plo­t(t­ime­_va­riable, variab­leO­fIn­terest)
slice time variable
timeVa­ria­ble­["st­art­-da­te":­"­end­-da­te"]

Time-s­eries with different variables

fix, ax = plt.subplots()
ax.plot(time_variable, variable1, color = "blue")
ax.set_xlabel()
ax.set_ylabel()

ax2 = ax.twinx()     # same x-axis but different y-axis
ax2.plot(time_variable, variable2, color = "red")
ax2.set_xlabel()
ax2.set_ylabel()
plt.show()

Add annota­tions

#  First argument  is the text of the annotation
#  xy argument  is the xy of the dataset to which the annotation has to refer (pandas object)
#  xytext argument  is the xy coordinate of the text
#  arrowprops  a dictionary that defines the properties of the arrow we would like to use 
ax.annotate("", xy = , xytext = , arrowprops = {})

# the arguments for the arrowprops
https://matplotlib.org/tutorials/text/annotations.html
Annota­tions are small pieces of text refering to a particular part of the graph.

Bar chart

fig, ax = plt.subplots()
ax.bar(x-axis, y-axis)
plt.show()

barchart

ax.set­_xt­ick­lab­els­(names)
change the names on the x axis
ax.set­_yl­abe­l("")
Change name of the y axis
ax.bar­(x,y, bottom = , label = "­"))
Important that you use the same x values, set bottom= equal to the pd.series containing the data whereon you want to stack.
ax.leg­end()
ax.set­_xt­ick­lab­els(x, rotation = 90)
If you want to turn the x labels 90 degrees.
You can keep adding bars to eachother by calling ax.bar­(bo­ttom) multiple times.H­ow­ever, you have to add the different series in bottom:
"­med­als­["Go­ld"] + medals­["Si­lve­r"]"

Histogram

fix, ax = plt.subplots()
ax.hist(x, label = "", bins = value/list, histtype = , label = "")
ax.set_xlabel("")
ax.set_ylabel("")

Boxplot

fig, ax = plt.subplots()
ax.boxplot(x)
ax.set_ylabel()

# Create multiple boxplots
fig, ax = plt.subplots()
ax.boxplot([mens_rowing["Height"], mens_gymnastics["Height"]])
ax.set_xticklabels(["Rowing", "Gymnastics"])

Scatte­rplot

fix, ax = plt.subplots()

ax.scatter(x, y, color = "" , label = "")

# create mutiple scatters on the same plot with different colors
fix, ax = plt.subplots()
ax.scatter(x, y, color = "red", label ="")
ax.scatter(x, y, color = "blue", label = "")
ax.legend()
ax.set_xlabel()
ax.set_ylabel()


# encoding a third variable by color
fig, ax = plt.subplots()
ax.scatter(x, y, c = )

Changing plot style

# This has to be before the subplots method
plt.style.use("ggplot")

# The available styles
https://matplotlib.org/gallery/style_sheets/style_sheets_reference.html

Sharing your visual­iza­tions

# save figure
fig.savefig("name.png")