The matplotlib plotting library for Python (part of pylab) makes publication quality figures that are easy to modify and save.
The following line makes the output appear inside an IPython notebook, instead in a separate window. (This isn't needed in Wakari, but it won't hurt.)
%matplotlib inline
The example below plots $\cos(2\pi t)$ vs. $t$.
from pylab import *
t = linspace(0.0, 2.0, 100)
y = cos(2*pi*t)
figure()
plot(t, y)
show()
The first line loads pylab
library.
The linspace
command returns a list of evenly spaced numbers from the first argument to the second argument, where the number of elements is given by the third argument. Many of the predefined functions in Python are “vectorized” which means that they can accept a list as input. For example, when the cos
function has an argument t that is a list, it will return a list. That means that y
will be a list containing the cosines of the elements in the list t
.
The figure
command opens a new figure window. If you want a second plot to appear in a different figure, you should put another figure
command before the next plot
command. If you want multiple plots to appear in a single figure, all of the plot
commands should be below a single figure
command.
The first argument of the plot
command contains the horizontal coordinates and the second contains the vertical coordinates. In other words, the example above makes a plot of y
vs. t
.
The show
command tells Python to draw any figures. It should appear after the last
plotting command.
Some options for the linestyle
(or ls
) argument are:
- = solid
-- = dashed
: = dotted
-. = dash-dot
The color
(or c
) argument sets the color of the line. Some of the options are:
r = red
g = green b = blue
k = black
c = cyan
m = magenta
y = yellow
w = white
The linewidth
argument adjust the thickness of the line.
from pylab import *
t = linspace(0.0, 2.0, 100)
y = cos(2*pi*t)
figure()
plot(t, y, ls='--', color='r', linewidth=2)
show()
Axis labels can be added with the xlabel
and ylabel
commands. A caption can be added with the title
command.
The grid
command can be used to add a grid to the figure. The color
argument can be used with this command.
You could also manually set the limits on the axes with the xlim
and ylim
commands, which take two arguments for the lower and upper limits.
from pylab import *
t = linspace(0.0, 2.0, 100)
y = cos(2*pi*t)
figure()
plot(t, y)
xlabel('time (s)')
ylabel('voltage (mV)')
title('A Simple Plot')
grid()
xlim(0,1.5)
ylim(-1.5,1.5)
show()
In the examples above, the points are connected by lines, but there are so many points that the curve looks smooth. In the plot
command, it is optional to add markers for each point on the list. Some of the options for marker
argument are:
. = points o = circles s = squares D = diamonds
h = hexagons 8 = octagons ^ = up triangles
v = down triangles
The markersize
(or ms
) argument is a number used to set the size of the markers. The linestyle
(or ls
) can also be set to None
to show only the markers, which is preferable for most data.
The example below uses fewer points so that the markers don't overlap.
from pylab import *
t = linspace(0.0, 2.0, 40)
y = cos(2*pi*t)
figure()
plot(t, y, ls='None', marker='o', ms=5)
show()
Instead of the plot
command, the scatter
command can be used to make a scatter plot, which is useful for plotting data. The s
argument is an integer used to set the size, instead of markersize
. With the scatter
command, you don't have to specify that there is no line. Also, some space is automatically left around the data points (compare the plot below to the one above).
from pylab import *
t = linspace(0.0, 2.0, 40)
y = cos(2*pi*t)
figure()
scatter(t, y, marker='o', s=25)
show()
The errorbar
command can be used to plot data with error bars. The third argument contains the uncertainties for the vertical direction. The optional fourth argument contains the uncertainties for the horizontal direction. Note that this is the opposite order as for the coordinates of the points, because the horizontal uncertainties are optional.
Unfortunately, the default for the errorbar
command is to connect the points with a line, not to use markers. You should always set the linestyle
(or ls
) to None
. You can also set the marker
in the errorbar
command. You may need to adjust the markersize
(or ms
) so the the error bars are visible.
from pylab import *
x = array([1,2,3,4,5])
y = array([0.9,4.1,8.7,16.5,24.9])
xerr = array([0.1,0.1,0.1,0.1,0.1])
yerr = array([0.6,0.9,0.75,0.9,1.2])
figure()
errorbar(x, y, yerr, xerr, ls='None', marker='o', ms=4)
show()
An alternative is to use the scatter
command to make a scatter plot, and to use the errorbar
command to add error bars. In this example, only vertical error bars are used. Note that this method leaves more space around the data points.
from pylab import *
x = array([1,2,3,4,5])
y = array([0.9,4.1,8.7,16.5,24.9])
yerr = array([0.6,0.9,0.75,0.9,1.2])
figure()
scatter(x,y)
errorbar(x, y, yerr, ls='None')
show()
One of the axes can be made logarithmic with the semilogx
or semilogy
function.
Both axes can be made logarithmic using the loglog
function. It is simplest to make graph using plot
, scatter
, or errorbar
followed by a command make one or both axes logarithmic as shown below.
For logarithmic scales, including grid lines makes it much easier to estimate values on a graph. The command
grid(which='both')will put grid lines at both the major tick marks and at the minor tick marks in between.
from pylab import *
x = array([1,2,3])
y = array([10,80,200])
figure()
scatter(x,y)
semilogy()
grid(which='both')
show()
If a logarithmic horizontal axis is used on the horizontal axis, it is better to use the logspace
function to plot a curve (for example, a theoretical curve). It returns returns a list of numbers from 10 to the power of the first argument to 10 to the power of the second argument, where the number of elements is given by the third argument. The numbers will be evenly spaced on a logarithmic scale. For example, logspace(2,4,50)
will return 50 numbers from $10^2 = 100$ to $10^4 = 10000$. In the example below, not how much smoother the curve made using the logspace
function is, especailly for small $x$. The curve made with the linspace
function only has two points with $x<100$.
from pylab import *
xtheory1 = linspace(10, 1000, 20)
ytheory1 = 1.0/(xtheory1+10.)**2
xtheory2 = logspace(1, 3, 20)
ytheory2 = 1.0/(xtheory2+10.)**2
figure()
plot(xtheory1,ytheory1,label='linspace',c='b')
plot(xtheory2,ytheory2,label='logspace',c='g')
semilogx()
legend()
show()
As mentioned earlier, multiple plots can appear in the same figure. If you want multiple plots to appear in a single figure, all of the plotting commands should be below a single figure
command. When there are multiple plots, it is helpful to make a legend to label them. This is done be adding a label
argument to each plotting command and using the legend command. The loc
argument can be used to specify the location of the legend.
from pylab import *
xtheory = linspace(0.0, 5.0, 100)
ytheory = xtheory**2
xdata = array([1,2,3,4,5])
ydata = array([0.9,4.1,8.7,16.5,24.9])
yerr = array([0.6,0.9,0.75,0.9,1.2])
figure()
plot(xtheory,ytheory,label='theory')
errorbar(xdata, ydata, yerr, ls='None', marker='o',label='data')
legend(loc='upper left')
show()
The previous example shows how to get a smooth curve if you're using a logarithmic scale on the horizontal axis.
If you create a figure outside of IPython, the following toolbar will appear below it.
from IPython.display import Image
Image(filename="matplotlib-toolbar.png")
this button, do either of the following: (a) Press the left mouse button and hold it, dragging it to a new position. When you release it, the data under the point where you pressed will be moved to the point where you released. (b) Press the right mouse button, dragging it to a new position. The x axis will be zoomed in proportionate to the rightward movement and zoomed out proportionate to the leftward movement. 2. The fifth button is the “Zoom to rectangle” button. Click the button to activate this mode. Put your mouse somewhere over an axis and press the left mouse button. Drag the mouse while holding the button to a new location and release. The axis view limits will be zoomed to the rectangle you have defined. 3. The first button is the “Home” button, which will restore the original view. 4. The last button is the “Save” button. A figure can be saved as one of the following image types: PNG, PS, EPS, SVG.
Further information is available at:
http://matplotlib.sourceforge.net/users/pyplot_tutorial.html (a good place to start)
http://matplotlib.sourceforge.net/ (links to documentation for all commands)