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

Combined Cheatsheet

Uploaded by

User070213
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
67 views

Combined Cheatsheet

Uploaded by

User070213
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

Engineering Programming If Statements Functions

If statements are used to test for particular conditions and Functions are named blocks of code, designed to do one
Cheat Sheet respond appropriately.
Conditional tests
specific job. Information passed to a function is called an
argument, and information received by a function is called a
parameter.
equals x == 42
Variables and strings not equal x != 42 A simple function
greater than x > 42
Variables are used to store values. A string is a series of characters, def greet_user():
or equal to x >= 42 print("Hello!")
surrounded by single or double quotes. less than x < 42 greet_user()
Hello world or equal to x <= 42
Passing an argument
print(“Hello world!”) Conditional test with lists
def greet_user(username):
Concatenation (combining strings) first_bike = bikes[0] """Display a personalized greeting."""
'trek' in bikes print("Hello, " + username + "!")
first_name = 'albert'
'surly' not in bikes greet_user('jesse')
last_name = 'einstein'
full_name = first_name + ' ' + last_name Default values for parameters
Dictionaries def make_pizza(topping='bacon'):
Lists Dictionaries store connections between pieces of """Make a single-topping pizza."""
A list stores a series of items in a particular order. You access items information. Each item in a dictionary is a key-value pair. print("Have a " + topping + " pizza!")
make_pizza()
using an index, or within a loop. A simple dictionary make_pizza('pepperoni')
Make a list alien = {'color': 'green', 'points': 5}
Returning a value
bikes = ['trek', 'redline', 'giant'] Accessing a value def add_numbers(x, y):
Get the first item in a list print("The alien's color is " + alien['color']) """Add two numbers and return the sum."""
return x + y
first_bike = bikes[0] Adding elements sum = add_numbers(3, 5)
Get the last item in a list alien['x_position'] = 0 print(sum)
last_bike = bikes[-1] alien.update({'size': 42, 'eyes': 3})
Looping through all key-value pairs Working with Files
Looping through a list
fav_numbers = {'eric': 17, 'ever': 4} Your programs can read from files and write to files.
for bike in bikes:
for name, number in fav_numbers.items():
print(bike)
print(name + ' loves ' + str(number))
Path
Adding items to a list Absolute (complete location) - D:\documents\mydocument.doc
Looping through all keys Relative (to the current directory) - mydocument.doc
bikes = [] for name in fav_numbers.keys():
bikes.append('trek') print(name + ' loves a number')
Opening a file
list3 = list1 + list2 path = 'mydocument.doc'
Looping through all the values mode = 'r'
Making numerical lists
for number in fav_numbers.values(): with open(path, mode) as f:
squares = [] print(str(number) + ' is a favorite') pass
for x in range(1, 11):
squares.append(x**2) Creating a dict from a pair of lists Modes
mapping = dict(zip(key_list, value_list)) 'r' read-only
List comprehensions
'w' write-only, erasing existing file
squares = [x**2 for x in range(1, 11)]
User Input 'a'
'r+'
append to existing file
read and write
Slicing a list
Your programs can prompt the user for input. All input is stored as a Reading and writing
finishers = ['sam', 'bob', 'ada', 'bea'] string.
first_two = finishers[:2] with open('demo.txt', 'w') as f:
Prompting for a value 2 f.writelines("one text line %d\n" %i for i in range(4))
Copying a list with open('demo.txt', 'r') as f:
name = input("What's your name? ")
copy_of_bikes = bikes[:] print("Hello, " + name + "!") 2 lines = f.readlines()
Prompting for numerical input
Zip 3 Out: ['line 0\n', 'line 1\n', 'line 2\n', 'line 3\n']
age = input("How old are you? ")
zip “pairs” up the elements of a number of lists, tuples, or other age = int(age) KISS – Keep It Short and Simple
sequences to create a list of tuples: pi = input("What's the value of pi? ")
seq1 = ['foo', 'bar', 'baz'] pi = float(pi) Simple is better than complex
seq2 = ['one', 'two'] If you have a choice between a simple and a complex solution, and
zipped = zip(seq1, seq2) both work, use the simple solution. Your code will be easier to
list(zipped) maintain, and it will be easier for you and others to build on that
Out: [('foo', 'one'), ('bar', 'two')] code later on.
NumPy Array Mathematics Subsetting, Slicing, Indexing
Arithmetic Operations Subsetting
Import Convention > a[2] Select the element at the 2nd
> a – b Substraction
> import numpy as np > np.substract(a, b) index
> b + a Addition > b[1,2] Select the element at row 1
NumPy Arrays > np.add(a, b) column 2
> a / b Division (equivalent to b[1][2] )
> np.divide(a, b)
> a * b Multiplication Slicing
> np.multiply(a, b) > a[0:2] Select items at index 0 and 1
axis 0
> np.exp(b) Exponentiation

axis 0 > np.sqrt(b) Square root > b[0:2,1] Select items at rows 0 and 1 in
> np.sin(a) Sine column 1
> np.cos(b) Cosine
> np.log(a) Natural logarithm Select all items at row 0
> a.dot(b) Dot product > b[:1] (equivalent to b[0:1, :] )
> np.cross(a, b) Cross product

axis 2
axis 0 axis 1 axis 1 Comparison > c[1,…] Same as [1,:,:]
> a == b array([[[ 3., 2., 1.],

Data Types array([[False, True, True],


[False, False, False]])
Element-wise comparison
> a[::-1]
[ 4., 5., 6.]]])
Reversed array a, -1 is step
> np.int64 Signed 64-bit integer types > a <= 2 Element-wise comparison array([3, 2, 1])
> np.float32 Standard double-precision floating point array([True, False, False])
Boolean Indexing
> np.complex Complex numbers represented by 128 floats > np.array_equal(a, b) Array-wise comparison Select elements from a less than
> a[a<2] 2
> np.bool Boolean type storing TRUE and FALSE values > np.all(a, axis) Test whether all array elements along

> np.object Python object type > np.all(a==b) a given axis evaluate to True
Fancy Indexing
> np.string_ Fixed-length string type Aggregate Functions > b[[1, 0, 1, 0],[0, 1, 2, 0]] Select elements (1,0) , (0,1) ,
> np.unicode_ Fixed-length unicode type (1,2) and (0,0)
> a.sum() Array-wise sum array([ 4. , 2. , 6. , 1.5])
Creating Arrays >
>
a.min()
b.max(axis=0)
Array-wise minimum value
Maximum value of an array row > b[[1, 0, 1, 0]][:,[0,1,2,0]] Select a subset of the matrix’s
> arr = [1,2,3] > b.cumsum(axis=1) Cumulative sum of the elements rows and columns
array([[ 4., 5., 6., 4.],
> a = np.array(arr) > a.mean() Mean
[ 1.5, 2., 3., 1.5],
> b = np.array([(1.5,2,3) (4,5,6)], > b.median() Median
> a.corrcoef() Correlation coefficient [ 4., 5., 6., 4.],
dtype = float)
> np.std(b) Standard deviation [ 1.5, 2., 3., 1.5]])
> c = np.array([[(1.5,2,3), (4,5,6)],

Array Manipulation
[(3,2,1), (4,5,6)]], dtype = float)
Sorting Arrays
> np.zeros(shape = (3,4)) Create an array of zeros
> a.sort() Sort an array
> np.ones(shape, dtype) Create an array of ones Transposing Array
> c.sort(axis=0) Sort the elements of an array’s axis
> d = np.arange(start, stop, step) Create an array of evenly spaced > i = np.transpose(b) Permute array dimensions
values (step value) > i.T
> np.linspace(start, stop, number) Create an array of evenly spaced Change Array Shape
values (number of samples) > b.reshape(3,-2) Reshape, but don’t change data
> np.full(shape, fill_value) Create an array filled with fill_value Adding/Removing Elements
> np.eye(N) Create a NxN identity matrix > h.resize(shape=(2,6)) Return a new array with shape
> np.random.randint(low, high, size) Create an array with random int values
> np.append(h,g) Append items to an array
> np.empty(shape) Create an empty array
> np.insert(arr,index,vals,axis) Insert items in an array
> e = np.copy(a) Create a copy of the array
> np.delete(arr,index,axis) Delete items from an array
Combining Arrays
Inspecting your Array > np.concatenate((a,d),axis) Concatenate arrays
> a.shape Array dimensions > np.vstack((a,b)) Stack vertically (row-wise)
> len(a) Length of array > np.hstack((a,b)) Stack horizontally (column-wise)
> b.ndim Number of array dimensions > np.column_stack((a,b)) Create stacked column-wise
> e.size Number of array elements
> b.dtype Data type of array elements arrays
> b.dtype.name Name of data type
Engineering Programming Cheatsheet (c) 2021 Thibault Thétier
> b.astype(int) Convert an array to a different type
Released under a CC‐BY 4.0 International License
Python For Data Science Cheat Sheet Asking For Help Dropping
>>> help(pd.Series.loc)
>>> s.drop(['a', 'c']) Drop values from rows (axis=0)
Pandas Basics Selection Also see NumPy Arrays >>> df.drop('Country', axis=1) Drop values from columns(axis=1)
Learn Python for Data Science Interactively at www.DataCamp.com
Getting
>>> s['b'] Get one element Sort & Rank
-5
Pandas >>> df.sort_index() Sort by labels along an axis
>>> df.sort_values(by='Country') Sort by the values along an axis
>>> df[1:] Get subset of a DataFrame
The Pandas library is built on NumPy and provides easy-to-use Country Capital Population >>> df.rank() Assign ranks to entries
data structures and data analysis tools for the Python 1 India New Delhi 1303171035
2 Brazil Brasília 207847528
programming language. Retrieving Series/DataFrame Information
Selecting, Boolean Indexing & Setting Basic Information
Use the following import convention: By Position >>> df.shape (rows,columns)
>>> import pandas as pd >>> df.iloc([0],[0]) Select single value by row & >>> df.index Describe index
'Belgium' column >>> df.columns Describe DataFrame columns
Pandas Data Structures >>> df.iat([0],[0])
>>>
>>>
df.info()
df.count()
Info on DataFrame
Number of non-NA values
Series 'Belgium'
Summary
A one-dimensional labeled array a 3 By Label
>>> df.loc([0], ['Country']) Select single value by row & >>> df.sum() Sum of values
capable of holding any data type b -5
'Belgium' column labels >>> df.cumsum() Cummulative sum of values
>>> df.min()/df.max() Minimum/maximum values
c 7 >>> df.at([0], ['Country']) >>> df.idxmin()/df.idxmax()
Index Minimum/Maximum index value
d 4 'Belgium' >>> df.describe() Summary statistics
>>> df.mean() Mean of values
>>> s = pd.Series([3, -5, 7, 4], index=['a', 'b', 'c', 'd'])
By Label/Position >>> df.median() Median of values
>>> df.ix[2] Select single row of
DataFrame Country
Capital
Brazil
Brasília
subset of rows Applying Functions
Population 207847528 >>> f = lambda x: x*2
Columns
Country Capital Population A two-dimensional labeled >>> df.ix[:,'Capital'] Select a single column of >>> df.apply(f) Apply function
>>> df.applymap(f) Apply function element-wise
data structure with columns 0 Brussels subset of columns
0 Belgium Brussels 11190846 1 New Delhi
of potentially different types 2 Brasília Data Alignment
1 India New Delhi 1303171035
Index >>> df.ix[1,'Capital'] Select rows and columns
2 Brazil Brasília 207847528 Internal Data Alignment
'New Delhi'
NA values are introduced in the indices that don’t overlap:
Boolean Indexing
>>> data = {'Country': ['Belgium', 'India', 'Brazil'], >>> s3 = pd.Series([7, -2, 3], index=['a', 'c', 'd'])
>>> s[~(s > 1)] Series s where value is not >1
'Capital': ['Brussels', 'New Delhi', 'Brasília'], >>> s[(s < -1) | (s > 2)] s where value is <-1 or >2 >>> s + s3
'Population': [11190846, 1303171035, 207847528]} >>> df[df['Population']>1200000000] Use filter to adjust DataFrame a 10.0
b NaN
>>> df = pd.DataFrame(data, Setting
c 5.0
columns=['Country', 'Capital', 'Population']) >>> s['a'] = 6 Set index a of Series s to 6
d 7.0

I/O Arithmetic Operations with Fill Methods


You can also do the internal data alignment yourself with
Read and Write to CSV Read and Write to SQL Query or Database Table
the help of the fill methods:
>>> pd.read_csv('file.csv', header=None, nrows=5) >>> from sqlalchemy import create_engine >>> s.add(s3, fill_value=0)
>>> df.to_csv('myDataFrame.csv') >>> engine = create_engine('sqlite:///:memory:') a 10.0
>>> pd.read_sql("SELECT * FROM my_table;", engine) b -5.0
Read and Write to Excel c 5.0
>>> pd.read_sql_table('my_table', engine) d 7.0
>>> pd.read_excel('file.xlsx') >>> pd.read_sql_query("SELECT * FROM my_table;", engine) >>> s.sub(s3, fill_value=2)
>>> pd.to_excel('dir/myDataFrame.xlsx', sheet_name='Sheet1') >>> s.div(s3, fill_value=4)
read_sql()is a convenience wrapper around read_sql_table() and
Read multiple sheets from the same file >>> s.mul(s3, fill_value=3)
read_sql_query()
>>> xlsx = pd.ExcelFile('file.xls')
>>> df = pd.read_excel(xlsx, 'Sheet1') >>> pd.to_sql('myDf', engine) DataCamp
Learn Python for Data Science Interactively
Basic plots Scales API Tick locators API Animation API

P. ROUGIER
756

DESIGNED BY NICOLAS
plot([X],Y,[fmt],…) API ax.set_[xy]scale(scale,…) from matplotlib import ticker import matplotlib.animation as mpla
Cheat sheet
432 Version 3.2 X, Y, fmt, color, marker, linestyle
0.0 linear
0.0 log
ax.[xy]axis.set_[minor|major]_locator(locator)

1 2.5 - + any values


2.5 10 1 logit
0 + values > 0 ticker.NullLocator() T = np.linspace(0,2*np.pi,100)

Quick start 765 1234567 X,scatter(X,Y,…) 0.0


API 2 0 2 symlog
0.0 ticker.MultipleLocator(0.5)
S = np.sin(T)
line, = plt.plot(T, S)
423
API
0.0 0.5 1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0

2.5 1000100 2.5 1


Y, [s]izes, [c]olors, markers, cmap - any values
+ 0 < values < 1
0 1 ticker.FixedLocator([0, 1, 5]) def animate(i):
import numpy as np
1 0 1 5 line.set_ydata(np.sin(T+i/50))

6754 1234567 x,bar[h](x,height,…)


import matplotlib as mpl ticker.LinearLocator(numticks=3)
import matplotlib.pyplot as plt API
Projections
2 API
0.0 2.5 5.0
anim = mpla.FuncAnimation(
plt.gcf(), animate, interval=5)
ticker.IndexLocator(base=0.5, offset=0.25)

321 height, width, bottom, align, color


subplot(…,projection=p)
0.25 0.75
ticker.AutoLocator()
1.25 1.75 2.25 2.75 3.25 3.75 4.25 4.75 plt.show()

765 1234567 imshow(Z,[cmap],…)


X = np.linspace(0, 2*np.pi, 100) 0 1 2 3 4 5
p=’polar’ p=’3d’
API ticker.MaxNLocator(n=4) Styles
3421
Y = np.cos(X) 0.0 1.5 3.0 4.5
API
Z, cmap, interpolation, extent, origin
ticker.LogLocator(base=10, numticks=15)
fig, ax = plt.subplots() 103 104 105 106 107 108 109 1010 plt.style.use(style)

6754 1234567 contour[f]([X],[Y],Z„…)


ax.plot(X,Y,color=’C1’) API
p=Orthographic() API default classic grayscale
1.0 1.0 1.0
from cartopy.crs import Cartographic
Tick formatters
3 X, Y, Z, levels, colors, extent, origin 0.5 0.5

21
0.5
API
fig.savefig(“figure.pdf”) 0.0

0.5
0.0
0.5
0.0

0.5

fig.show()
765 1234567 quiver([X],[Y],U,V,…)
from matplotlib import ticker 1.0
0 1 2 3 4 5 6
1.0
0 1 2 3 4 5 6 7 1.0
0 1 2 3 4 5 6 7

ax.[xy]axis.set_[minor|major]_formatter(formatter)
API ggplot seaborn fast

3421
1.0 1.0 1.0

Anatomy of a figure
X, Y, U, V, C, units, angles Lines 0.5
0.5 0.5

API ticker.NullFormatter() 0.0 0.0 0.0


0.5 0.5 0.5

765 1234567 pie(X,[explode],…) linestyle or ls


1.0
ticker.FixedFormatter(['', '0', '1', ...]) 1.0 1.0
0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7

API 0 0.25 0.50 1 0.75 0.25 2 0.50 0.75 3 0.25 0.50 0.75 4 0.25 0.50 5
bmh Solarize_Light2 seaborn-notebook
Anatomy of a figure
432
1.0
1.0 1.0
Z, explode, labels, colors, radius "-" ":" "--" "-." (0,(0.01,2)) ticker.FuncFormatter(lambda x, pos: "[%.2f]" % x)
4 0.5 0.5 0.5

1 capstyle or dash_capstyle
Title Blue signal [0.00] [1.00] [2.00] [3.00] [4.00] [5.00] 0.0 0.0 0.0

Major tick Red signal 0.5 0.5 0.5

765 1234567T x, y, text, va, ha, size, weight, transform


Legend ticker.FormatStrFormatter('>%d<') 1.0 1.0 1.0

"butt" "round" "projecting"


0 1 2 3 4 5 6 0 1 2 3 4 5 6 0 1 2 3 4 5 6 7

text(x,y,text,…) API >0< >1< >2< >3< >4< >5<

432 TEX
Minor tick
ticker.ScalarFormatter()
3
Quick reminder
1
0 1 2 3 4 5
Major tick label Grid
Markers API ticker.StrMethodFormatter('{x}')

765 1234567 X,fill[_between][x](


Line
(line plot) 0.0 1.0 2.0 3.0 4.0 5.0 ax.grid()
… ) API

432 ticker.PercentFormatter(xmax=5) ax.patch.set_alpha(0)


Y axis label

2 Y1, Y2, color, where 0% 20% 40% 60% 80% 100%

1 '.' 'o' 's' 'P' 'X' '*' 'p' 'D' '<' '>' '^' 'v' ax.set_[xy]lim(vmin, vmax)
ax.set_[xy]label(label)
1234567
Y axis label Markers
Ornaments
(scatter plot) '1' '2' '3' '4' '+' 'x' '|' '_' 4 5 6 7 ax.set_[xy]ticks(list)
1 Advanced plots ax.set_[xy]ticklabels(list)
ax.legend(…)
765
'$ $''$ $''$ $''$ $''$ $''$ $''$ $''$ $''$ $''$ $''$ $''$ $' API ax.set_[sup]title(title)
Spines step(X,Y,[fmt],…) API markevery handles, labels, loc, title, frameon ax.tick_params(width=10, …)
Figure
Axes
432
Line
(line plot) X, Y, fmt, color, marker, where 10 [0, -1] (25, 5) [0, 25, -1] title ax.set_axis_[on|off]()
0
1
0 0.25 0.50 0.75 1 1.25 1.50 1.75 2 2.25 2.50 2.75 3 3.25 3.50 3.75 4 Legend
765 1234567 X,boxplot(X,…)
label
Minor tick label
X axis label handletextpad handle
markerfacecolor (mfc)
ax.tight_layout()
X axis label API
Colors
432
handlelength
API plt.gcf(), plt.gca()
notch, sym, bootstrap, widths Label 1 Label 3 mpl.rc(’axes’, linewidth=1, …)
1
1 C0 C1 C2 C3 C4 C5 C6 C7 C8 C9 labelspacing markeredgecolor (mec)
Subplots layout
’Cn’ fig.patch.set_alpha(0)
0
Label 2 Label 4
765 246 X,errorbar(X,Y,xerr,yerr,…)
API
0 b 2 g 4 r 6 c 8 m 10 y 12 k 14 w 16 ’x’
API 1 DarkRed Firebrick Crimson IndianRed Salmon borderpad
text=r’$\frac{-e^{i\pi}}{2^n}$’

fig, axs = plt.subplots(3,3) 4


’name’ columnspacing numpoints or scatterpoints
10 (1,0,0) (1,0,0,0.75) (1,0,0,0.5) (1,0,0,0.25)
312
subplot[s](cols,rows,…) API Y, xerr, yerr, fmt 0 2 4 6 8 10 12 14 16 (R,G,B[,A])
10 #FF0000 borderaxespad
0 2 4 #FF0000BB
6 8 #FF000088
10 12 #FF000044
14 16 ’#RRGGBB[AA]’
10 0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0 Keyboard shortcuts API

71
61
51 1234567 X,hist(X, bins, …) API
0
0
0
2
2
4
4
6
6
8
8
10 12 14 16 ’x.y’
10 12 14 16 ax.colorbar(…) API

41
ctrl + s Save ctrl + w Close plot

31
G = gridspec(cols,rows,…) API bins, range, density, weights mappable, ax, cax, orientation
ax = G[0,:]
21
111 Colormaps API
r Reset view f Fullscreen 0/1

765 1234567 violinplot(D,…) View forward


f b View back
API plt.get_cmap(name) 0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0

423
ax.inset_axes(extent)
p Pan view o Zoom to rect
API D, positions, widths, vert

1 Uniform x X pan/zoom y Y pan/zoom


ax.annotate(…)
6754 1234567 barbs([X],[Y],
viridis API g Minor grid 0/1 G Major grid 0/1
U, V, …) API magma text, xy, xytext, xycoords, textcoords, arrowprops
l X axis log/linear L Y axis log/linear

321
d=make_axes_locatable(ax) plasma
API X, Y, U, V, C, length, pivot, sizes
ax=d.new_horizontal(’10%’) Sequential Annotation
Ten Simple Rules
765 1234567 eventplot(positions,…) xytext xy
Greys READ
API YlOrBr textcoords ycoords

423 positions, orientation, lineoffsets Wistia 1. Know Your Audience


Getting help 1 Diverging 2. Identify Your Message

6754 1234567 X, Y, C, gridsize, bins


Spectral 3. Adapt the Figure
hexbin(X,Y,C,…) API
matplotlib.org coolwarm
Event handling 4. Captions Are Not Optional
321
API
github.com/matplotlib/matplotlib/issues RdGy 5. Do Not Trust the Defaults

0.2500
discourse.matplotlib.org Qualitative fig, ax = plt.subplots() 6. Use Color Effectively
stackoverflow.com/matplotlib
0.1875
0.1250
0.0625 1234567 X, Y, normed, detrend
xcorr(X,Y,…) API
tab10 def on_click(event): 7. Do Not Mislead the Reader

0.0000
gitter.im/matplotlib tab20 print(event) 8. Avoid “Chartjunk”
twitter.com/matplotlib 0.0625
0.1250
0.1875
Cyclic fig.canvas.mpl_connect( 9. Message Trumps Beauty
Matplotlib users mailing list
0.2500 twilight ’button_press_event’, on_click) 10. Get the Right Tool
Axes adjustements API Uniform colormaps Color names API Legend placement How do I …
black floralwhite darkturquoise … resize a figure?
L K J
plt.subplot_adjust( … ) k darkgoldenrod cadetblue
viridis
dimgray goldenrod powderblue → fig.set_size_inches(w,h)
plasma dimgrey cornsilk lightblue
gray gold deepskyblue … save a figure?
grey lemonchiffon skyblue
→ fig.savefig(”figure.pdf”)
A 7 8 9 I
inferno
darkgray khaki lightskyblue
magma darkgrey palegoldenrod steelblue
silver darkkhaki aliceblue … save a transparent figure?
lightgray ivory dodgerblue
top axes width
cividis lightgrey beige lightslategray → fig.savefig(”figure.pdf”, transparent=True)
gainsboro lightyellow lightslategrey
whitesmoke lightgoldenrodyellow slategray … clear a figure?
w olive slategrey
→ ax.clear()
Sequential colormaps white
snow
y
yellow
lightsteelblue
cornflowerblue
rosybrown olivedrab royalblue … close all figures?
B 4 5 6 H

figure height
lightcoral yellowgreen ghostwhite
axes height indianred darkolivegreen lavender → plt.close(”all”)
Greys brown greenyellow midnightblue
firebrick chartreuse navy … remove ticks?
hspace Purples maroon lawngreen darkblue → ax.set_xticks([])
darkred honeydew mediumblue
Blues r darkseagreen b … remove tick labels ?
red palegreen blue
Greens mistyrose lightgreen slateblue → ax.set_[xy]ticklabels([])
salmon forestgreen darkslateblue

C 1 2 3 G
left bottom wspace right Oranges tomato limegreen mediumslateblue … rotate tick labels ?
darksalmon darkgreen mediumpurple
Reds coral g rebeccapurple → ax.set_[xy]ticks(rotation=90)
orangered green blueviolet
YlOrBr lightsalmon lime indigo … hide top spine?
sienna seagreen darkorchid
D E F
figure width seashell mediumseagreen darkviolet
YlOrRd chocolate springgreen mediumorchid → ax.spines[’top’].set_visible(False)
OrRd saddlebrown mintcream thistle … hide legend border?
sandybrown mediumspringgreen plum
peachpuff mediumaquamarine violet → ax.legend(frameon=False)
Extent & origin API
PuRd peru
linen
aquamarine
turquoise
purple
darkmagenta ax.legend(loc=”string”, bbox_to_anchor=(x,y))
RdPu bisque lightseagreen m … show error as shaded region?
darkorange mediumturquoise fuchsia → ax.fill_between(X, Y+error, Y‐error)
ax.imshow( extent=…, origin=… ) BuPu burlywood azure magenta 1: lower left 2: lower center 3: lower right
antiquewhite lightcyan orchid … draw a rectangle?
GnBu tan paleturquoise mediumvioletred 4: left 5: center 6: right
navajowhite darkslategray deeppink → ax.add_patch(plt.Rectangle((0, 0),1,1)
origin="upper" origin="upper" PuBu blanchedalmond darkslategrey hotpink 7: upper left 8: upper center 9: upper right
5
(0,0) (0,0) papayawhip teal lavenderblush … draw a vertical line?
YlGnBu moccasin darkcyan palevioletred
orange c crimson A: upper right / (‐.1,.9) B: right / (‐.1,.5) → ax.axvline(x=0.5)
PuBuGn wheat aqua pink
oldlace cyan lightpink C: lower right / (‐.1,.1) D: upper left / (‐.1,‐.1) … draw outside frame?
BuGn E: upper center / (.5,‐.1) F: upper right / (.9,‐.1)
0
(4,4) (4,4) → ax.plot(…, clip_on=False)
extent=[0,10,0,5] extent=[10,0,0,5] YlGn G: lower left / (1.1,.1) H: left / (1.1,.5)
Image interpolation API
I: upper left / (1.1,.9) J: lower right / (.9,1.1)
… use transparency?
5
origin="lower" origin="lower" → ax.plot(…, alpha=0.25)
(4,4) (4,4)
Diverging colormaps K: lower center / (.5,1.1) L: lower left / (.1,1.1) … convert an RGB image into a gray image?
→ gray = 0.2989*R+0.5870*G+0.1140*B
(0,0) (0,0) PiYG Annotation connection styles API … set figure background color?
0
extent=[0,10,0,5] extent=[10,0,0,5] PRGn
→ fig.patch.set_facecolor(“grey”)
0 10 0 10
BrBG
arc3, arc3, angle3, … get a reversed colormap?
None none nearest
rad=0 rad=0.3 angleA=0,
angleB=90
→ plt.get_cmap(“viridis_r”)
PuOr
… get a discrete colormap?
Text alignments API RdGy
→ plt.get_cmap(“viridis”, 10)
RdBu
ax.text( …, ha=… , va=…, … ) … show a figure for one second?
RdYlBu
→ fig.show(block=False), time.sleep(1)

Matplotlib
RdYlGn
angle, angle, arc,
Spectral angleA=-90, angleA=-90, angleA=-90,
(1,1)
bilinear bicubic spline16 Performance tips
angleB=180, angleB=180, angleB=0,
top coolwarm rad=0 rad=25 armA=0,
armB=40,
rad=0
center bwr
baseline seismic scatter(X, Y) slow
bottom plot(X, Y, marker=”o”, ls=””) fast
(0,0)
left center right
for i in range(n): plot(X[i]) slow
Qualitative colormaps bar, bar, bar, plot(sum([x+[None] for x in X],[])) fast
fraction=0.3 fraction=-0.3 angle=180,
fraction=-0.2

Text parameters API Pastel1 spline36 hanning hamming cla(), imshow(…), canvas.draw() slow
im.set_data(…), canvas.draw() fast
Pastel2
ax.text( …, family=… , size=…, weight = …)
Paired
ax.text( …, fontproperties = … )
Accent Beyond Matplotlib
The quick brown fox xx-large (1.73)
Dark2

The quick brown fox x-large (1.44)


Set1
Annotation arrow styles
Seaborn: Statistical Data Visualization
The quick brown fox large (1.20) Set2
hermite kaiser quadric
API Cartopy: Geospatial Data Processing
The quick brown fox medium (1.00) Set3 yt: Volumetric data Visualization
The quick brown fox small (0.83)
mpld3: Bringing Matplotlib to the browser
The quick brown fox x-small (0.69) tab10 - <- ->
The quick brown fox xx-small (0.58)
tab20 Datashader: Large data processing pipeline
The quick brown fox jumps over the lazy dog black (900) tab20b
plotnine: A Grammar of Graphics for Python
The quick brown fox jumps over the lazy dog bold (700)
The quick brown fox jumps over the lazy dog semibold (600) tab20c <-> <|- -|>
The quick brown fox jumps over the lazy dog normal (400)
The quick brown fox jumps over the lazy dog ultralight (100)
Miscellaneous colormaps
catrom gaussian bessel Matplotlib Cheatsheets (c) 2020 Nicolas P. Rougier
Released under a CC‐BY 4.0 International License
The quick brown fox jumps over the lazy dog monospace <|-|> ]-[ ]-
The quick brown fox jumps over the lazy dog serif
The quick brown fox jumps over the lazy dog sans
The quick brown fox jumps over the lazy dog cursive
terrain
ocean -[ |-| simple
The quick brown fox jumps over the lazy dog italic
The quick brown fox jumps over the lazy dog normal cubehelix
rainbow
The quick brown fox jumps over the lazy dog
The quick brown fox jumps over the lazy dog
small-caps
normal twilight mitchell sinc lanczos fancy wedge

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy