Easy Graph Plotting with Pyplot

By Monty, 7th May 2015

Simple_GraphGraphs (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 & 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:

Wikipedia:

matplotlib is a plotting library for the Python programming language and its numerical mathematics extension NumPy. It provides an object-oriented API for embedding plots into applications using general-purpose GUI toolkits like Tkinter, wxPython, Qt, or GTK+. There is also a procedural "pylab" interface based on a state machine (like OpenGL), designed to closely resemble that of MATLAB, though its use is discouraged. SciPy makes use of matplotlib.

matplotlib was originally written by John D. Hunter, has an active development community, and is distributed under a BSD-style license. Michael Droettboom was nominated as matplotlib's lead developer shortly before John Hunter's death in 2012.

As of 23 June 2017, matplotlib 2.0.x supports Python versions 2.7 through 3.6. Matplotlib 1.2 is the first version of matplotlib to support Python 3.x. Matplotlib 1.4 is the last version of matplotlib to support Python 2.6.

What do you think?

Leave a Reply

%d bloggers like this: