Plotting in Python can be done with the pyplot
part of the matplotlib module. With matplotlib you can create high-quality figures and graphics and also plot and visualize your results. Matplotlib is open source and freely available software, [21]. The matplotlib website also contains excellent documentation with examples, [35]. In this section, we will show you how to use the most common features. The examples in the upcoming sections assume that you have imported the module as:
from matplotlib.pyplot import *
In case you want to use the plotting commands in IPython, it is recommended that you run the magic command %matplotlib
directly after starting the IPython shell. This prepares IPython for interactive plotting.
The standard plotting function is plot
. Calling plot(x,y)
creates a figure window with a plot of y as a function of x. The input arguments are arrays (or lists) of equal length. It is also possible to use plot(y)
, in which case the values in y will be plotted against their index, that is, plot(y)
is a short form of plot(range(len(y)),y)
.
Here is an example that shows how to plot sin(x) for x ϵ [-2π, 2π] using 200 sample points and sets markers at every fourth point:
# plot sin(x) for some interval x = linspace(-2*pi,2*pi,200) plot(x,sin(x)) # plot marker for every 4th point samples = x[::4] plot(samples,sin(samples),'r*') # add title and grid lines title('Function sin(x) and some points plotted') grid()
The result is shown in the following figure (Figure 6.1):
Figure 6.1: A plot of the function sin(x) with grid lines shown.
As you can see, the standard plot is a solid blue curve. Each axis gets automatically scaled to fit the values but can also be set manually. Color and plot options can be given after the first two input arguments. Here, r*
indicates red star-shaped markers. Formatting is covered in more detail in the next section. The title
command puts a title text string above the plot area.
Calling plot
multiple times will overlay the plots in the same window. To get a new clean figure window, use figure()
. The figure
command might contain an integer, for example, figure(2)
, which can be used to switch between figure windows. If there is no figure window with that number, a new one is created, otherwise, the window is activated for plotting and all subsequent plotting commands apply to that window.
Multiple plots can be explained using the legend
function, along with adding labels to each plot call. The following example fits polynomials to a set of points using the commands polyfit
and polyval
, and plots the result with a legend:
# —Polyfit example— x = range(5) y = [1,2,1,3,5] p2 = polyfit(x,y,2) p4 = polyfit(x,y,4) # plot the polynomials and points xx = linspace(-1,5,200) plot(xx, polyval(p2, xx), label='fitting polynomial of degree 2') plot(xx, polyval(p4, xx), label='interpolating polynomial of degree 4') plot(x,y,'*') # set the axis and legend axis([-1,5,0,6]) legend(loc='upper left', fontsize='small')
Here you can also see how to manually set the range of the axis using axis([xmin,xmax,ymin,ymax])
. The legend
command takes optional arguments on placement and formatting; in this case the legend is put in the upper-left corner and typeset with a small font size, as shown in the following figure (Figure 6.2).
Figure 6.2: Two polynomials fitted to the same points.
As final examples for basic plotting, we demonstrate how to do scatter plots and logarithmic plots in two dimensions.
Example of 2D point scatter plot:
# create random 2D points import numpy x1 = 2*numpy.random.standard_normal((2,100)) x2 = 0.8*numpy.random.standard_normal((2,100)) + array([[6],[2]]) plot(x1[0],x1[1],'*') plot(x2[0],x2[1],'r*') title('2D scatter plot')
Figure 6.3(a): An example of a scatter plot
The following code is an example of a logarithmic plot using loglog
:
# log both x and y axis x = linspace(0,10,200) loglog(x,2*x**2, label = 'quadratic polynomial', linestyle = '-', linewidth = 3) loglog(x,4*x**4, label = '4th degree polynomial', linestyle = '-.', linewidth = 3) loglog(x,5*exp(x), label = 'exponential function', linewidth = 3) title('Logarithmic plots') legend(loc = 'best')
Figure 6.3(b): An example of a plot with logarithmic x and y axis
The examples shown in the preceding figure (Figure 6.3(a) and Figure 6.3(b)) used some parameters of plot
and loglog
which allow special formatting. In the next section, we will explain the parameters in more detail.
18.117.71.211