Arange and Plotting
Numpy and Matplotlib Basics 1
Learning Outcomes
- use the
arange
function to create time vectors
- create figures, plot data, add labels and legends, and save figures
Arange
- function from
numpy
- create an array over a range
- usage:
vect = arange(start, stop, step)
t = arange(0,1,0.01)
Sin, Cos, and Pi
- I assume these
numpy
functions and variables are obvious
-
class
nooverlay
Plotting Functions
From matplotlib.pyplot
:
figure
clf
plot
xlabel
ylabel
legend
savefig
clf
- clear the current figure
- usage:
matplotlib
turns “hold” on by default
- subsequent runs of your code will draw onto the same figure
- use
clf
sort of as a replacement for close all
(Matlab)
- you can use
close('all')
, but your code will run a little slower
plot
plot(x,y)
- actually plot
y
vs. x
on the current axis
- several different formats:
plot(x, y, 'r:')
plot(x, y, label='$y_1$')
- makes legend creation very easy, but can only handle one x/y
pair per
plot
command
plot(x1, y1, x2, y2)
plot(x1, y1, 'r-', x2, y2, 'g-.')
- keep in mind that hold is on by default
xlabel
xlabel("Time (sec.)")
- add a string to the x-axis label
Scientific string note
matplotlib
supports sub-scripts, super-scripts, and symbols
using LaTeX syntax with dollar signs $
:
$y_1$
$x^2$
$\\theta$
- note that you have to escape the backslash
ylabel
ylabel("$y_1(t)$")
- add a string to the y-axis label
legend
- main usages:
legend([label1, label2])
legend([label1, label2], loc=2)
- if you labeled all your plots:
savefig
- save the current figure to a file
- optionally specify dpi if saving to png
savefig("fig1.png", dpi=300)
savefig("fig1.eps")
- I mainly use png for websites and eps for documents
- I convert eps to pdf using a shell script
- direct pdf support may have improved over the years
- from the help: “Most backends support png, pdf, ps, eps and svg”
- I haven’t played with svg
- png is easy to stick in a Word document, but pixelation usually
leads to poor print quality