0% found this document useful (0 votes)
13 views

Justin1209 Matplotlib

Uploaded by

TOP 10
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Justin1209 Matplotlib

Uploaded by

TOP 10
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Matplotlib Cheat Sheet

by Justin1209 (Justin1209) via cheatography.com/101982/cs/21196/

Import Library Linestyles (cont)

from matpl​otlib import pyplot as plt alpha= 0.1 - 1

Basic Line Plot Boiler​plate Styles:


x_values plt.st​yle.us​e(​"​fiv​eth​irt​yei​ght​")
days = [0, 1, 2, 3, 4, 5, 6] plt.st​yle.us​e(​"​ggp​lot​")
y_val​ues1
plt.st​yle.us​e(​"​sea​bor​n")
mone​y_spent = [10, 12, 12, 10, 14, 22, 24]
plt.st​yle.us​e(​"​def​ault​ ")
y_val​ues2
mone​y_s​pent_2 = [11, 14, 15, 15, 22, 21, 12]
Legends plot key
assigend to one plot
plt.p​lo​t(days, money_​spe​nt) # Create Legend

plt.p​lo​t(days, money_​spe​nt_2) plt.le​gen​d([​"​ fi​rst​_li​ne​", "​ se​con​d_l​ine​ ", loc=])

plt.show() # loc Number​code


1 upper left

Subplots 2 upper right


draw more than one plot in figure
3 lower left
# Create subplots
4 lower right
plt.su​bpl​ot(​ rows, columns, index​_of​_su​bplot)
5 right
# Example
6 center left
# First Subplot
7 center right
plt.su​bpl​ot(1, 2, 1)
8 lower center
plt.pl​ot(x, y, color=​'gr​een')
9 upper center
# Second Subplot
10 center
plt.su​bpl​ot(1, 2, 2)
plt.pl​ot(x, y, color=​'st​eel​blue') loc specifies the legends location (if not specified: finds "​bes​t"
# Format Subplots location)

plt.su​bpl​ots​_ad​jus​t( ​arg​uem​ents)
Figures
left, right, top, bottom -mar​gin
wspace, hspace hori​zon​tal​/ve​rtical margin between # Create Figure with custom size
plots plt.fi​gur​e(f​igs​ize​=( ​width, heigth ))
plt.pl​ot(x, y)
The object that contains all subplots is called figure
plt.sa​vef​ig(​'ta​ll_​and​_na​rro​w. png/ .svg/ .pdf')
Always put specific Attributes (color, markers, ...) for a subplot
directly under plt.p​lot() When we’re making lots of plots, it’s easy to end up with lines that
have been plotted and not displa​yed. If we’re not careful, these
Linestyles “forgo​tten” lines will show up in your new plots. In order to be sure

plt.pl​ot(x, y, sty​le​=" ") that you don’t have any stray lines, you can use the command plt.c​‐
lo​se(​'al​l') to clear all existing plots before you plot a new one.
Keywords to put in for style:

color= green, #AAAAAA


line​sty​le= dotted: :, dashed: -- or -.
mark​er= o, *, s, x, d, h
line​wid​th= 1, 2, ...

By Justin1209 (Justin1209) Published 22nd November, 2019. Sponsored by Readable.com


cheatography.com/justin1209/ Last updated 13th January, 2020. Measure your website readability!
Page 1 of 3. https://readable.com
Matplotlib Cheat Sheet
by Justin1209 (Justin1209) via cheatography.com/101982/cs/21196/

Modify Ticks Stacked Bars

# Specify subplot to modify # We use the keyword bottom to do this


ax1 = plt.su​bpl​ot(​ row, column, index) # The top bar will have bottom set as height
# Attrib​utes # First Bar
ax1.se​t_x​tic​ks([1, 2, 4]) video_​gam​e_hours = [1, 2, 2, 1, 2]
ax1.se​t_y​tic​ks(​[ 0.1, 0.2, ...]) plt.ba​r(r​ang​e(l​en(​vid​eo_​gam​e_h​ours)),
ax1.se​t_x​tic​kla​bel​s([​"​Jan​", "​Feb​", "​Apr​"], rota​‐ ​ ​vid​eo_​gam​e_h​ours)
tio​n=30) # Second Bar
# rota​tio​n=d​egr​ees rotates the labels book_hours = [2, 3, 4, 2, 1]
ax1.se​t_y​tic​kla​bel​s([​"​10%​", "​20%​", ...]) plt.ba​r(r​ang​e(l​en(​boo​k_h​ours)),
​ ​boo​k_h​ours,
We have to do it this way, even if we only have one plot
​ ​ b​ott​om​=v​ide​o_g​ame​_hours)

Axis and Labels # Get each bottom for 3+ bars


sport_​hours = np.add​(vi​deo​_ga​me_​hours, book_h​ours)
Zoom in or out of the plot:
If we want to compare "di​fferent sub-at​tri​butes from one attrib​ute​" we
plt.ax​is(​x_​min, x_max, y_min, y_max)
can use stacked bar charts. For example:
Labeling the Axes:
Attr​ibu​te: Entert​ainment hours
plt.xl​abe​l("str ")/ plt.yl​abel() / plt.ti​tle() Sub-​Att​rib​utes: Gaming, Reading, ...

Add Text to Graph Error Bars


plt.text(x_coord, y_coord, "text"); # Use the keyword yerr to repersent the error
range
Simple Bar Chart values = [10, 13, 11, 15, 20]
plt.b​ar​(ra​nge​(le​n(y​_va​lues)), y_valu​es) yerr = [1, 3, 0.5, 2, 4] # singe value possible

We use rang​e(l​en(​y_v​alu​es)) to get a tick for each value we want to plt.bar(y, x, yerr​=​yerr, caps​ize​=10)

represent in the Bar Chart plt.show()

If we want to present an uncert​ainty Range within a Bar Chart we


Scatter Plot can use Error Bars
plt.scatter(x_values, y_values)
Fill Between (Line Plot)
Side-B​y-Side Bars x = range(3)
# We have to specifiy the location of each Dataset y = [10, 12, 13]
in the Plot using this pattern: y_lo​wer = [8, 10, 11]
n = ? # Number of specific dataset y_up​per = [i + 2 for i in y_values]
t = ? # Number of datasets # Calculate a % deviat​ion
d = ? # Number of sets of bars y_lo​wer​_bo​und = [element - (element * error_​in_​‐
w = 0.8 # Width of each bar dec​imal) for element in origin​al_​lis​t_o​f_y​_va​lues]
x_values1 = [t*el​ement + w*n for element in #this is the shaded error
range(d)] plt.fi​ll_​bet​ween(x, y_lower, y_upper, alpha ​=0.2)
# Get x_values in the middle of both bars #this is the line itself
middle_x = [ (a + b) / 2.0 for a, b in zip(x_​val​‐ plt.pl​ot(x, y)
ues1, x_valu​es2)] plt.show()

Returns a shaded are around the line

By Justin1209 (Justin1209) Published 22nd November, 2019. Sponsored by Readable.com


cheatography.com/justin1209/ Last updated 13th January, 2020. Measure your website readability!
Page 2 of 3. https://readable.com
Matplotlib Cheat Sheet
by Justin1209 (Justin1209) via cheatography.com/101982/cs/21196/

Pie Chart

payment_names = ["Card Swipe", "Cash", "Apple


Pay", "Other"]
paymen​t_freqs = [270, 77, 32, 11]
# Creating Pie Chart
plt.pi​e(p​aym​ent​_freqs)
plt.ax​is(​'eq​ual')
# Two Methods for Labeling
# First Method
plt.le​gen​d(p​aym​ent​_names)
# Second Method (directly when creating)
plt.pi​e(p​aym​ent​_freqs, labels​=pa​yme​nt_​names)
Show percen​tages of total in each slice:
plt.pi​e(p​aym​ent​_freqs, labels​=pa​yme​nt_​names, auto​‐
pct​='%​0.1​f%%')
# autopct takes a string formatting instru​ction
# %d%% -> round to decimal
plt.show()

Histogram

# Create one Histogram


plt.hi​st(​dat​aset, range=​(0,​100), bins​=20)
# Specifiy number of bins (default = 10)
# Create multiple Histog​rams
plt.hi​st(a, alph​a​=0.5, norm​ed​=True)
plt.hi​st(b, hist​typ​e​='s​tep', line​wid​th=2 norm​ed​‐
=True)

# Specify alpha for opacity or use hist​type to draw just the outline
# Use line​width to specifiy the linewidth of the outline
# Use the keyword normed to normalize the histog​rams

Norm​alize divides the x_values by a constat such that the area


under the curve sums to 1

By Justin1209 (Justin1209) Published 22nd November, 2019. Sponsored by Readable.com


cheatography.com/justin1209/ Last updated 13th January, 2020. Measure your website readability!
Page 3 of 3. https://readable.com

You might also like