Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
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 vs. .
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 .
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 vs. .
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.
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.
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.
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).
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).
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.
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.
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 to . In the example below, not how much smoother the curve made using the logspace function is, especailly for small . The curve made with the linspace function only has two points with .
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.
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.
Additional Documentation
Further information is available at:
https://matplotlib.org/stable/tutorials/pyplot.html (a good place to start)
https://matplotlib.org/stable/users/index.html