Contact Us!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.

| Download
Views: 57
Visibility: Unlisted (only visible to those who know the link)
Image: ubuntu2204
Kernel: Python 3 (system-wide)

An Introduction to Making Plots with Python

The matplotlib plotting library for Python (part of pylab) makes publication quality figures that are easy to modify and save.

1. A Simple Example

The example below plots cos(2πt)\cos(2\pi t) vs. tt.

import pylab as pl t = pl.linspace(0.0, 2.0, 100) y = pl.cos(2*pl.pi*t) pl.figure() pl.plot(t, y) pl.show()
Image in a Jupyter notebook

The first line loads pylab library. (Note that the numpy library has some of the same functions, like linspace and arrary, but not the plotting funcitons.)

The linspace function 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 functions in Python are “vectorized” which means that they can accept a list (or array) as input. For example, when the cos function has an argument t that is a list, it will return a list. That means that tt.

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 yy vs. tt.

The show command tells Python to draw any figures. It should appear after the last plotting command.

2. More Plotting Options

a. Customizing a Line

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.

import pylab as pl t = pl.linspace(0.0, 2.0, 100) y = pl.cos(2*pl.pi*t) pl.figure() pl.plot(t, y, ls='--', color='r', linewidth=2) pl.show()
Image in a Jupyter notebook

b. Labels and Limits

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.

import pylab as pl t = pl.linspace(0.0, 2.0, 100) y = pl.cos(2*pl.pi*t) pl.figure() pl.plot(t, y) pl.xlabel('time (s)') pl.ylabel('voltage (mV)') pl.title('A Simple Plot') pl.grid() pl.xlim(0,1.5) pl.ylim(-1.5,1.5) pl.show()
Image in a Jupyter notebook

c. Markers, Scatter Plots, and Error Bars

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.

import pylab as pl t = pl.linspace(0.0, 2.0, 40) y = pl.cos(2*pl.pi*t) pl.figure() pl.plot(t, y, ls='None', marker='o', ms=5) pl.show()
Image in a Jupyter notebook

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).

import pylab as pl t = pl.linspace(0.0, 2.0, 40) y = pl.cos(2*pl.pi*t) pl.figure() pl.scatter(t, y, marker='o', s=25) pl.show()
Image in a Jupyter notebook

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. You can adjust the size of the lines at the ends of the error bars with capsize (the default is zero for no lines).

import pylab as pl x = pl.array([1,2,3,4,5]) y = pl.array([0.9,4.1,8.7,16.5,24.9]) xerr = pl.array([0.1,0.1,0.1,0.1,0.1]) yerr = pl.array([0.6,0.9,0.75,0.9,1.2]) pl.figure() pl.errorbar(x, y, yerr, xerr, ls='None', marker='o', ms=4, capsize=2) pl.show()
Image in a Jupyter notebook

An alternative is to use the scatter command to make a scatter plot, then 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.

import pylab as pl x = pl.array([1,2,3,4,5]) y = pl.array([0.9,4.1,8.7,16.5,24.9]) yerr = pl.array([0.6,0.9,0.75,0.9,1.2]) pl.figure() pl.scatter(x,y) pl.errorbar(x, y, yerr, ls='None', capsize=2) pl.show()
Image in a Jupyter notebook

d. Logarithmic Axes

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.
import pylab as pl x = pl.array([1,2,3]) y = pl.array([10,80,200]) pl.figure() pl.scatter(x,y) pl.semilogy() pl.grid(which='both') pl.show()
Image in a Jupyter notebook

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 102=10010^2 = 100 to 104=1000010^4 = 10000. In the example below, not how much smoother the curve made using the logspace function is, especailly for small xx. The curve made with the linspace function only has two points with x<100x<100.

import pylab as pl xtheory1 = pl.linspace(10, 1000, 20) ytheory1 = 1.0/(xtheory1+10.)**2 xtheory2 = pl.logspace(1, 3, 20) ytheory2 = 1.0/(xtheory2+10.)**2 pl.figure() pl.plot(xtheory1,ytheory1,label='linspace',c='b') pl.plot(xtheory2,ytheory2,label='logspace',c='g') pl.semilogx() pl.legend() pl.show()
Image in a Jupyter notebook

3. Overlaying Plots

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.

import pylab as pl xtheory = pl.linspace(0.0, 5.0, 100) ytheory = xtheory**2 xdata = pl.array([1,2,3,4,5]) ydata = pl.array([0.9,4.1,8.7,16.5,24.9]) yerr = pl.array([0.6,0.9,0.75,0.9,1.2]) pl.figure() pl.plot(xtheory,ytheory,label='theory') pl.errorbar(xdata, ydata, yerr, ls='None', marker='o',capsize=2, label='data') pl.legend(loc='upper left') pl.show()
Image in a Jupyter notebook

The previous example shows how to get a smooth curve if you're using a logarithmic scale on the horizontal axis.

4. Saving a Figure to a File

Use the savefig funciton to save a figure to a file. The supported formats are eps, pdf, pgf, png, ps, raw, rgba, svg, and svgz. The following example makes a figure and saves it as a png file.

import pylab as pl t = pl.linspace(0.0, 2.0, 100) y = pl.cos(2*pl.pi*t) pl.figure() pl.plot(t, y) pl.savefig('test.png')
Image in a Jupyter notebook

Additional Documentation