We give an introduction to plotting using Matplotlib.

Matplotlib

The Matplotlib library is a plotting library that is commonly used for producing publication quality figures of all kinds. Matplotlib has many features (too many to cover here). The easiest way to create a plot is to use the example gallery found on the Matplotlib website. Find the type of plot and features that you want and use the code sample provided.

To illustrate the kinds of plots that we will generate, consider the following example. The code below produces a plot of and on the interval .

==============================
 
import numpy as np  
import matplotlib.pyplot as plt  
 
x = np.linspace(-10,10,100)  
y1 = 5*x**2-400  
y2 = x**3-x+1  
plt.plot(x,y1,color=’blue’,label=’$f(x)$’)  
plt.plot(x,y2,color=’red’,label=’$g(x)$’)  
plt.xlabel(’$x$’)  
plt.ylabel(’$y$’)  
plt.legend()  
plt.title(’A graph of $f(x)$ and $g(x)$’)  
plt.show()  
==============================

The code above covers the main plotting features we will use in this course. The meaning of each line is covered below.

  • import matplotlib.pyplot as plt - imports the appropriate Matplotlib functions with the commonly used alias plt
  • np.linspace(-10,10,100) - produces an array containing 100 evenly spaced points from -10 to 10
  • plt.plot - adds the data points to the image, additional arguments specify their color and add a label for the plot legend (use plt.scatter to draw points without connecting them)
  • plt.xlabel, plt.ylabel - adds axes labels
  • plt.legend - adds a legend to the graph
  • plt.title - adds a title to the graph
  • plt.show - displays the graph

Note that the inputs for np.plot can be regular lists. In this case we choose to use arrays due to ease of use.

Problems

Note that for the questions below, the hints contain the solutions.

Use the Matplotlib library to plot and on .
Use the Matplotlib library to create a scatter plot (using plt.scatter) of using 20 points on the interval .

Workspace