The Python standard library consists of packages (folders) containing modules (Python code files) to perform various tasks.
To make one available in your code, use
import <package or module name>
To make it available under a different (usually shorter) name, use
import <package or module name> as <nickname>
To import a module from a package or to import a sub-package, use
from <higher-level item> import <lower-level item>
The as
keyword can still be used.
import numpy as np
from matplotlib import pyplot as plt
With numpy
, the best way to load data, as long as all of the data
are numerical, is with
np.loadtxt('<path-to-file>', <opts>...)
Common Options
delimiter
: a string indicating what characters separate the
columns (default: ' '
; usually, you'll want ','
)skiprows
: the number of rows to skip (default: 0
; set
to 1
if the columns have headings)usecols
: a tuple of integers specifying which columns to readunpack
: if True
, the output will be a tuple of arrays. If False
(the default), the output will be a single, 2D grid.max_rows
: the maximum number of rows to import. The default is to
import all of the rows.# CISV
data = np.loadtxt('LRC_resonant_data.csv', delimiter=',', skiprows=1)
data
Accessing an Element
In a normal Python 2D list, to access the second column in the fifth
row, you would use data[2][1]
. With a numpy array, use data[2,1]
.
data[2,1]
Accessing a Row
In a normal Python grid, getting a whole row is easy. To get the fifth
row, just use data[4]
. With a numpy array, that still works, but you
can also use data[4,:]
.
data[4]
data[4,:]
Accessing a Column
What's the point in the longer command? It suggests what to do to get
a whole column! In normal Python, you'd basically have to transpose
the array. Now, to get the whole second column, you can use data[:,1]
.
data[:,1]
Slicing in General
The :
is used for slicing, and it indicates a range. For a 2D numpy
array, the general syntax is
data[row_start:row_stop, col_start:col_stop]
If either start value is blank, numpy starts with the first. If either stop value is blank, numpy goes all the way to the end.
# CISV
data[0:10, 0:2]
Let's assign the two columns to separate variables.
# CISV
frequency = data[:,0]
voltage = data[:,1]
The following will make our plots interactive. Without this, plots would appear inline.
%matplotlib tk
The simplest way to make quick plots---when you just want to simply
visualize your data without much careful customization---is using
pyplot
(which we imported as plt
) from matplotlib
.
The basic syntax is
plt.plot(<xdata>, <ydata>, '<format_string>')
As always, we need to label our axes using
plt.xlabel(r'<xlabel>')
plt.ylabel(r'<ylabel>')
Note that we used raw strings for the labels. Why? Because
matplotlib
understands most LaTeX code, which uses backslashes
to indicate commands.
# CISV
plt.plot(frequency, voltage, 'b-')
plt.xlabel(r'$f$ (Hz)')
plt.ylabel(r'$V_\mathrm{L}$ (V)')
All the interesting stuff happens toward the lower frequencies. In a case like this, a logarithmic plot is more helpful. There are three kinds of log plots we can do:
plt.loglog
plt.semilogx
plt.semilogy
The arguments are the same as for plt.plot
. In this case, we want
plt.semilogx
.
# CISV
plt.semilogx(frequency, voltage)
plt.xlabel(r'$f$ (Hz)')
plt.ylabel(r'$V_\mathrm{L}$ (V)')
There are two common ways of creating new numpy
arrays:
np.arange(start, stop, step=1)
works like range
, but step
does not need to be an integer.
np.linspace(start, stop, num=50, endpoint=True)
produces an array of num
evenly-spaced points, including stop
if
endpoint=True
.
x1 = np.linspace(0, 10, 100)
x2 = np.linspace(0, 20, 100)
Unlike regular Python functions and operations on regular Python
lists, most numpy
operations act element-by-element.
We can do trig, or other mathematical functions, on the whole array at once.
# CISV
x1+x2
# CISV
y1 = np.sin(x1)
plt.plot(x1, y1)
# CISV
y2 = x2**2
plt.plot(x2, y2)
We could have created the log plot by taking the log first.
# CISV
log_f = np.log10(frequency)
plt.plot(log_f, voltage)
CISV
If a graph looks linear on a semilog-y plot, then the independent variable depends exponentially on the dependent variable.
x3 = np.linspace(0, 5, 100)
y3 = 10**x3
plt.semilogy(x3, y3)
CISV
If a graph looks linear on a semilog-x plot, then the independent variable depends logarithmically on the dependent variable.
x4 = np.linspace(0.001, 5, 100)
y4 = np.log10(x4)
plt.semilogx(x4, y4)
CISV
If an expression has the form
Then, defining , , and , this is
x5 = np.linspace(1, 30, 100)
y5a = 3*x5**2
y5b = 2*x5**3
plt.loglog(x5, y5a)
plt.loglog(x5, y5b)
plt.grid()
CISV
When , then . Then
Now select two points on the graph, so that
m5a = np.log(y5a[99]/y5a[50])/np.log(x5[99]/x5[50])
m5a
m5b = np.log(y5b[99]/y5b[50])/np.log(x5[99]/x5[50])
m5b