Graphs (also known as charts) are an indispensible visual aid for conveying a lot of data in an easy-to-digest form. Everyone is familiar with graphs in everyday life, such as those showing trends over time, e.g. world population, global warming, the cost of living, interest rates, etc. They are of fundamental importance in the STEM subjects for representing mathematical functions, theoretical predictions, and experimental observations. The computer makes it very easy to plot graphs quickly and accurately, especially when using graphics software systems like MATLAB (an industry-standard numerical computing environment and fourth-generation programming language).
Matplotlib is a plotting library for the Python programming language and its numerical mathematics extension NumPy. For simple plotting the pyplot interface provides a MATLAB-like interface. It’s usually used together with NumPy, but for this simple introduction we’ll leave it out till the final example.
The first example is about as simple as it gets: import some library functions, specify some data, say what to do with it (plot), and then ask to see it. Pyplot takes care of the rest: drawing axes, numbering them, and plotting the graph. We’ll add a title, labels, a grid, and a legend in the next examples.
# First_graph.py # Authour: Alan Richmond, Python3.codes from pylab import plot, show, bar y = [3,5,9,2,6,4,7,8,1,5] # a list of numbers plot(y) # draw the graph show() # show it to me! ''' for a barchart replace plot(y) with these: x = [i for i in range(10)] bar(x,y) '''
This one is a simple temperature conversion graph between Centigrade & Fahrenheit.
# Temperatures.py # Authour: Alan Richmond, Python3.codes import matplotlib.pyplot as plt # Range of scales between freezing to boiling water F = [32,212] # Fahrenheit C = [0,100] # Centigrade plt.title('Convert Centigrade / Fahrenheit') plt.ylabel('degrees Centigrade') plt.xlabel('degrees Fahrenheit') plt.xlim(32,212) # try commenting this out... plt.grid(True) plt.plot(F,C) plt.show()
The next example is more complete and shows how to use trig functions in Python:
# Graph_plotting.py # Authour: Alan Richmond, Python3.codes import matplotlib.pyplot as plt from math import sin, cos, pi npoints=50 x = [x*2*pi/npoints for x in range(npoints+1)] y1 = [sin(t) for t in x] y2 = [cos(t) for t in x] plt.figure(figsize=(10, 5)) plt.title('Sine and Cosine') plt.xlabel('t (radians)') plt.ylabel('red: sin (t), blue: cos (t)') plt.grid(True) plt.xlim(0,2*pi) plt.ylim(-1.1,1.1) plt.plot(x, y1, color="red", label="sine") plt.plot(x, y2, color="blue", label="cosine") plt.legend() plt.show()
And this final example illustrates creating a 3D plot, with NumPy.
# Mplot3d.py # Adapted from http://matplotlib.org/mpl_toolkits/mplot3d/ from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm # colour map import matplotlib.pyplot as plt import numpy as np # http://www.numpy.org/ ax = Axes3D(plt.figure()) # http://docs.scipy.org/doc/numpy/reference/generated/numpy.arange.html X = np.arange(-5, 5, 0.25) # Return evenly spaced values within an interval Y = np.arange(-5, 5, 0.25) # http://docs.scipy.org/doc/numpy/reference/generated/numpy.meshgrid.html X, Y = np.meshgrid(X, Y) # Return coordinate matrices from coordinate vectors R = np.sqrt(X**2 + Y**2) # Square roots of squares Z = np.sin(R) # Sine of that. # http://matplotlib.org/mpl_toolkits/mplot3d/tutorial.html#surface-plots ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.jet) plt.show()
For more about pyplot see:
- Pyplot tutorial
- matplotlib Tutorials
- Matplotlib: plotting by: Nicolas Rougier, Mike Müller, Gaël Varoquaux
One thought on “Easy Graph Plotting with Pyplot”