Basic Plotting in Python using Matplotlib¶

Modules - Basics¶

Last edited: October 15th 2019

The following is a brief introduction to plotting in Python, using the library matplotlib. From the matplotlib home page: "matplotlib tries to make easy things easy and hard things possible." Let's get started!

In [1]:
import matplotlib.pyplot as plt
# This command imports the matplotlib-package pyplot, and defines plt as an alias for pyplot
import numpy as np
# This imports the the NumPy (Numerical Python) package, aliased as np.


Above we have imported pyplot (a matplotlib package containing all useful functions for plotting), and numpy, a package for scientific computing with Python. You can learn more about numpy in this notebook. Also, notice how we have given shorter nicknames to both the numpy and pyplot import, in order to save some typing.

The very basics of plotting¶

We use the function plt.plot to plot. This command takes two arguments: a list of $x$-values and a list of $y$-values. Each pair of $x$- and $y$-values will be a point, and a line will be drawn between these points.

In [2]:
# Plot some arbitrary x- and y-values
x = [1, 2, 4, 6]  # List of x-values
y = [0, 4, -2, 8] # List of corresponding y-values
plt.plot(x, y)    # Function to plot the x and y points
plt.show()        # Not necessary in notebook, but required if running python from command line


Plotting a Function¶

Plotting a function $f$, given $$y=f(x)$$ along an interval $$x=[a,b].$$

Example:

We would like to plot the function $$f(x)=3x^2+x-1$$ for the interval $$x=[-1,2].$$

Step 1: Defining the range of $x$

We use the command

In [3]:
x = np.linspace(-1, 2, 301)  # Array of 301 linearly spaced points between -1 and 2


This creates an array of $301$ linearly spaced, discrete values of x between $-1$ and $2$. Here we used a function from the numpy library. If you are unfamiliar with numpy, and want to learn more about it, see [this] notebook.

Step 2: Using the plot command

As above, we use the plt.plot to plot the function.

In our case, we need to write

In [4]:
plt.plot(x, 3*x**2+x-1)  # Remember, first argument is x-values, second is y-values
plt.show()


Further Steps: Adding axes labels, a legend, a plot title, etc.

We often want to add axes labels, a legend, a title, a grid etc. to the plot. This is done by using the following commands:

In [5]:
plt.plot(x, 3*x**2+x-1, label="$f(x)$") # Label is the text that will appear in the legend
plt.ylabel('$f(x)$')                    # Label on y-axis.
# The dollar symbols means to use LaTeX
plt.xlabel('$x$')                       # Label on x-axis
plt.title('Plot of $f(x)=3x^2+x-1$')    # Plot title