The core plotting library in Python is matplotlib. The matplotlib gallery is a great way to figure out how to make the kind of plots you want. Just look for a plot of the right basic style and click on the image to see the code that generated it.
Two things that may differ a bit from other graphing programs that you are used to:
show() function. Several examples of using show() are included below.Generating basic bivariate plots is done using the plot() function.
import matplotlib.pyplot as plt
import numpy as np
#generate some data
x = np.array(range(20))
y = 3 + 0.5 * x + np.random.randn(20)
#plot the data
plt.plot(x, y, 'bo')
plt.show()
We can also scale any of the axes logarithmically.
fig = plt.loglog(x, y, 'rs')
fig = plt.semilogx(x, y, 'g^')
Histograms are made using the hist() function.
#generate some random numbers from a normal distribution
data = 100 + np.random.randn(500)
#make a histogram with 20 bins
plt.hist(data, 20)
plt.show()
We can add axis labels to a figure using the xlabel() and ylabel() functions.
plt.hist(data, 20)
plt.xlabel('Body Mass (g)', fontsize=20)
plt.ylabel('Number of Individuals', fontsize= 20)
Axis limits are changed using the axis([xmin, xmax, ymin, ymax]) function.
plt.hist(data, 20)
plt.axis([90, 110, 0, 100])
To plot multiple datasets together we tell Python not to overwrite the previous data using hold(True). Running hold(False) will cause Python to start overwriting the figure again.
x = np.array(range(20))
y = 3 + 0.5 * x + np.random.randn(20)
z = 2 + 0.9 * x + np.random.randn(20)
#plot the data
plt.plot(x, y, 'bo')
plt.hold(True)
plt.plot(x, z, 'r^')
plt.show()
Subplots are generated using subplot(#ofRows, #ofCols, Position).
plt.subplot(1, 2, 1)
plt.plot(x, y, 'rs')
plt.subplot(1, 2, 2)
plt.hist(data, 10)
plt.show()
Plotting multiple figures in the same script requires that we create new figures, which is done using figure(). In this example the two figures are different figures rather than subplots of a single figure.
plt.plot(z, x, 'go')
plt.figure()
plt.plot(z, y, 'rs')