Plotting in Python can be done by using the function plot from the module pyplot, which is part of a larger module called matplotlib. To use this function, you'll have to import it first.
import matplotlib.pyplot as plt
or
from matplotlib import pyplot as plt # both import statements
# have the same effect
Calling plt.plot(x,y) creates a figure window with a plot of $y$ as a function of $x$. Generally, the parameters that you pass to this plotting function are arrays of equal length; you can also plot individual points. Furthermore, if $y$ is an array, you can use plt.plot(y), in which case the values in $y$ will be plotted against their index; so, this statement is the same as plt.plot(range(len(y)), y). Study the basic example included below:
# plot of sin(x) on [-2*pi, 2*pi]
from matplotlib import pyplot as plt
import numpy as np
x = np.linspace(-2*np.pi, 2*np.pi, 200) # 200 equidistant points between -2*pi and 2*pi
plt.plot(x, np.sin(x),'r') # plot the graph of sin(x)
# add title: (optional)
plt.title('Simple plot of SIN(x)')
# add grid: (optional)
plt.grid()
plt.show() # depending on your installation, you need to include
# this to make sure that the plot is visible
This is a basic plotting script. You'll need to understand what it does before you can do more complicated things.
When this code is executed, a new window appears; that is the current window. Python will name it 'Figure 1' if no other windows are open. Inside the current figure, Python has drawn and labelled some axes; these are known as the current axes.
It is important to realise that 'np.sin(x)' in the plot command represents a one-dimensional array of values corresponding to each value in the $x$-array. The 'plt.plot' function combines them into pairs $(x[i], np.sin(x[i])$ for $i=0,2,\dots,len(x)-1$, and joins them by a red line. Because we have 200 points, these lines will give you the impression of a curve. Look what happens if the above statements are repeated, but this time with only 20 points along the $x$-axis:
# "coarse" plot of sin(x) on [-2*pi, 2*pi]
from matplotlib import pyplot as plt
import numpy as np
x = np.linspace(-2*np.pi, 2*np.pi, 200) # 200 equidistant points between -2*pi and 2*pi
#plt.plot(x, np.sin(x),'r') # plot the graph of sin(x)
sample = x[::10] # this choice of stride will give you 20 pts. in x
plt.plot(sample, np.sin(sample),'r',sample, np.sin(sample),'bo')
plt.title('Sampled plot of SIN(x)')
plt.grid()
plt.show()
The point to take away from here is that the smoothness of your plots will depend on how many $x$-values you consider.
If you want to plot a triangle with given vertices, you can do something like this:
from matplotlib import pyplot as plt
import numpy as np
# these are the coordinates of the vertices:
# A = (1,5)
# B = (4,11)
# C = (3,20)
x_coord = np.array([1, 4, 3, 1]) # stores x-coordinates
y_coord = np.array([5, 11, 20, 5]) # stores the y-coordinates
plt.plot(x_coord, y_coord, 'r', x_coord, y_coord,'ro') # plot triangle
plt.grid() # add grid
plt.show() # show plot
The two arrays that you supply to 'plt.plot' must be of exactly the same length. It is a common mistake to have one of the arrays containing one or more extra elements. If you can't remember exactly how many elements you'll get from a statement like a = np.arange(0,26,0.13), take a moment or two to type len(a) in the command window and find out.
Calling plt.plot multiple times will overlay the plots in the same window. To get a new clean window, use the command plt.figure(). This command might contain an integer, for example, plt.figure(2), which can be used to switch between figure windows. If there is no figure with that number, a new one is created, otherwise, the window is activated for plotting and all subsequent plotting commands apply to that window.
Plots in Python can be customised to make them look the way you want them to look. You should always write a script to generate your plot (next time you have to produce another plot, you can use your old script to refresh your memory...). Otherwise you'll find yourself re-typing a lot of commands just to change a label or the color of a single curve in your plot.
You can add labels to your axes:
# plot of y = (x+4)*(x-1)*(x-6)
from matplotlib import pyplot as plt
import numpy as np
x = np.linspace(-6, 8, 200) # 200 equidistant points between -2*pi and 2*pi
y = (x+4)*(x-1)*(x-6) # generates 200 values for y
plt.plot(x,y,'b')
plt.xlabel('x')
plt.ylabel('y')
plt.show()
Multiple plots can be explained using the legend function, alog with adding labels to each plot call.
# plot of y = (x+4)*(x-1)*(x-6) CUBIC
# AND of y = (x+2)*(x-5) QUADRATIC
from matplotlib import pyplot as plt
import numpy as np
x = np.linspace(-6, 8, 200) # 200 equidistant points between -2*pi and 2*pi
y1 = (x+4)*(x-1)*(x-6) # generates 200 values for y1
y2 = (x+2)*(x-5) # generate 200 value for y2
plt.plot(x, y1,'b', label='CUBIC')
plt.plot(x, y2, 'r', label='QUADRATIC')
plt.xlabel('x')
plt.ylabel('y')
plt.axis([-6, 8, -50, 200]) # set the axes limits
plt.legend(loc='upper left', fontsize='small')
plt.show()
# you must add labels in the plots if you want your legend to display correctly
# the text in your label will be used in the legend box -- see the output:
The above example shows you how to manually set the range of the axes using the general syntax:
axis([xmin, xmax, ymin, ymax])
# in the above example:
# xmin = -6
# xmax = 8
# ymin = -50
# ymax = 200
Note also that the legend command takes optional arguments on placements and formatting; in this case the legend was placed in the upper-left corner and typeset with a small fontsize, as shown in the above output.These are not the only options.
An important parameter for customising plots is linewidth, which allows you to control the thickness of the lines used in your plot. Other formatting options are included in the table below:

# plot of y = (x+4)*(x-1)*(x-6) CUBIC
# AND of y = (x+2)*(x-5) QUADRATIC
from matplotlib import pyplot as plt
import numpy as np
x = np.linspace(-6, 8, 60) # 200 equidistant points between -2*pi and 2*pi
y1 = (x+4)*(x-1)*(x-6) # generates 200 values for y1
y2 = (x+2)*(x-5) # generate 200 value for y2
plt.plot(x, y1,'b', linewidth=4, label='CUBIC')
plt.plot(x, y2, 'r', linewidth=4, linestyle='dashed',
label='QUADRATIC')
plt.xlabel('x')
plt.ylabel('y')
plt.axis([-6, 8, -50, 200]) # set the axes limits
plt.legend(loc='upper left', fontsize='small')
plt.show()
Sometimes, you'll want to save your plots to some file. The command plt.savefig allows you to save a figure as an image. Many image and file formats are supported -- they are specified by the filename's extension as
plt.savefig('test.pdf') # save to PDF format
plt.savefig('test.png') # saves to PNG format
You may want to place your saved images against a non-white background. For this, the 'transparent' parameter can be set to make the figure's background transparent:
plt.savefig('test.pdf', transparent=True)
If you plan to include your plots in some document, you then perhaps would like to reduce the amount of surrounding white space by setting the figure's bounding box tight around the plot:
plt.savefig('test.pdf', bbox_inches='tight')
Sometimes, you may want to include several related plots in a single figure window, by placing them side by side (e.g., in order to contrast some features, etc). Python provides a built-in function, plt.subplot. The syntax for this is:
subplot(M, N, p)
This divides the current figure window into a grid of cells with $M$ rows and $N$ columns, and then makes cell $p$ the active one. This last parameter must satisfy $1\leq p\leq M*N$ (note that the labelling of the cells does not start at $0$ in this case). Any plotting command issued now will affect cell number $p$.
Let's say that we want to illustrate the effect of $a$ on the graph of $y=sin(ax)$; this parameter changes the wavelength of the periodic pattern produced by the sine function.
# testing the subplot option....
from matplotlib import pyplot as plt
import numpy as np
a = [0.4, 1.0, 3.0, 10] # values of 'a' to be tested
x = np.linspace(0, 4*np.pi, 200) # 200 equidistant points, etc....
# the y-values for the SINE functions:
y1 = np.sin(a[0]*x)
y2 = np.sin(a[1]*x)
y3 = np.sin(a[2]*x)
y4 = np.sin(a[3]*x)
# subplots:
plt.subplot(2,2,1) # upper left
plt.plot(x,y1,'r')
plt.ylabel('y1')
plt.subplot(2,2,2) # upper right
plt.plot(x,y2,'g')
plt.ylabel('y2')
plt.subplot(2,2,3) # lower left
plt.plot(x,y3,'b')
plt.ylabel('y3')
plt.xlabel('x')
plt.subplot(2,2,4) # lower right
plt.plot(x,y4,'m')
plt.ylabel('y4')
plt.xlabel('x')
# enhance the appearance:
plt.tight_layout()
# make plot visible:
plt.show()
# plt.savefig('sin4.pdf') # uncomment if you want to save the file
Each 'plt.subplot' command above selects a subregion of the figure. The subsequent 'plt.plot'command sets up the axes and draws a plot in the current subplot region. If the labels on the vertical axes look bunched together (overlapping the other plots), one possible fix is to use 'plt.tight_layout()'. Other options are also available.
The official documentation for Matplotlib can be found at:
Lots of examples, here: