Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
27 views

Python Cheat Sheet

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

Python Cheat Sheet

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

Python Cheat Sheet - Plotting with Matplotlib

For Physical Chemistry 1 2020-2021

Import Libraries Customize data points Customize Axes


import matplotlib.pyplot as plt All these commands can be added within the plot plt.xlabel() Label your axis
import matplotlib.cm as cm using: np.linspace(20, 350, 40) Make a list of ticks
plt.plot(x, y, line_style, marker, color) plt.xticks(ticks) specify ticks on axis
plt.xticks([]) no ticks on axis
Create Data Line style plt.ylim(-0.2,3.3) specify axis range
Plotting Data linewidth=3 Select the thickness of the line
Provide both x- and y-coordinates as arrays or lists: Worked out example
x = [2, 4, 6, 8, 10]
y = [15, 30, 40, 20, 10] import numpy as np
Plotting a formula import matplotlib.pyplot as plt
Create a list or array of x-coordinates and a function
depending on x: x = np.linspace(0, 60, 1000)
x = np.linspace(0, 10, 100)
y = np.cos(x) x1 =[30, 35, 40, 45, 50, 55, 60]
y1 = [0.275, 0.386, 0.403, 0.431, 0.479, 0.506,
Type of markers 0.556]
Create Plot
plt.figure(figsize = (6,4), dpi = 150) plt.figure(figsize = (4, 4), dpi = 120)
plt.plot(x, 0.007*x+0.12, ’--’, color ="Red",
figsize = (6,4) figure size in inches label = "fit")
dpi = 150 150x150 pixels per square inch plt.scatter(x1, y1, marker = "P", color="C9",
label = "data")
Most basic form of a plot:
plt.title("Example Plot")
plt.plot(x, y)
plt.xlabel(’x-label’)
plt.show()
plt.ylabel(’y-label’)
Colors plt.xlim(30, 60)
Types of plots
These are the default colors matplotlib uses plt.ylim(0.2, 0.6)
plt.plot(x, y) Plot a function or plot plt.legend()
points connected by a line
plt.scatter(x, y) Plot data points only plt.show()
plt.bar(pos, height) Make a bar plot
plt.hist(freq, bins) Make a histogram

Labels and legends


Each plot set of data can be given a label:
plt.plot(x, y, label = "set 1")
plt.legend() Show legend
plt.legend(loc=1) Set location of
legend
plt.legend(prop={’size’: 7}) Alter size of
legend Specific colors can be specified using
plt.title() Make a title color= <colorcode>
Python Cheat Sheet - Basics
For Physical Chemistry 1 2020-2021

Importing Libaries Lists Loops


To import an external module: A list stores a series of items in a particular order. The standard syntax used in a for loop:
import package as alias The index starts at 0. for <variable> in <sequence>:
Creating a list # body_of_loop that has set of statements
Common examples: my_list = [1, 2, 3, 4, "yellow", "blue"] # which requires repeated execution
import numpy as np my_list2= [[1,2,3],[7,8,9]]
import matplotlib.pyplot as plt range(1, 20, 2) Create a sequence of numbers
Selecting elements from 1 to 19 in increments of 2
Variables and Data Types my_list[1] select item at index 1
The standard syntax used in a while loop:
my_list[-1] select last item
Variable Assignment while <Boolean comparison>:
my_list[1:3] select items with index 1 and 2
x = 5 #body_of_loop that tells what needs to
my_list[2:] select items after index 1
Calculations with variables #happen while the boolean comparison is true
x + y Sum of two variables my_list[:4] select items before index 4
x - y subtraction of two variables my_list[:] copy list
If statements
x*y Multiplication of two variables my_list2[1][2] get the item at index 2 of the list
at index 1 An example of using conditional statements. As with
x**y x to the power of y the loops, an indent is used to indicate what needs to
x/y x divided by y List Methods
my_list.append(5) add 5 at the end of the list happen.
x%y remainder of x divided by y my_list.remove(5) remove 5 from the list
Types my_list.reverse() reverse the order of the list if x > 5:
str() ’Hello’, ’five’, ’5’ string del(my_list[0:3]) remove a selection of the list print("f{x} is greater than five")
int() 5, 3, 1 integer len(my_list) give the length of the list elif x < 0:
float() 2.0, 5.55 float min(my_list) give the lowest item print("f{x} is negative")
bool() True, False Boolean max(my_list) give the highest item else:
print("f{x} is between zero and five")
Mathematical functions with Numpy Boolean Comparisons
Can be used to perform a on every element in an x == 2 Check if x is equal to 2 Functions
array (arr). x != y Check if x is not equal to y A function can be used in various ways to
Trigonometic functions x > 2 Check if x is larger than 2
np.sin(arr) take the sine function make python do something based on the vari-
x < 2 Check if x is smaller than 2 ables you put in. In the most simple form
np.cos(arr) cosine function x >= 2 Check if x is larger or equal to 2
np.tan(arr) tan function a mathematical function can be defined like:
x <= 2 Check if x is smaller or equal to 2 def name_function(variables):
np.arcsin(arr) sin−1 5 in my_list Check 5 is in my_list
np.arccos(arr) cos−1 return(type here your formula)
np.arctan(arr) tan−1
Numpy Arrays
np.pi numerical value of pi
Exponentials np.array([1,2,3,4,5]) Make an array
np.exp(arr) e to the power of arr np.zeros(5) Make an array of length
np.log(arr) natural logarithm of arr 5 with zeros
np.log10() logarithm with base 10 np.linspace(0,100,8) Make an array 8 evenly
Other spaced values between 0
np.sqrt(arr) square root and 100
np.amax(arr) find the maximum value in arr np.arange(0,50,2) Make an array from 0 to
np.amin(arr) find the minimum value in arr 50 in steps of 2

You might also like