Skip to main content

Section 1.3 Matplotlib and 2D graphing

Matplotlib is a Python library that uses NumPy arrays (Section 1.2) to create static or interactive graphs and data visualizations. In this section we will learn how to use the MatPlotLib to graph curves and plot points in 2D.

Subsection Creating a graph or plot

A Matplotlib API (Application Programming Interface) called pyplot is used to create the figure and individual graphs. The figure acts as a container and can contain multiple subplots, each an axes object.
You can also create a figure and a plot with just one line of code using a comma to separate the two and the function plt.subplots() that creates both at once.

Subsection Curves in 2D

Matplotlib graphs curves by plotting points and connecting the dots. The inputs and outputs are given by NumPy arrays and then plotted on the axes.
Read through both sets of code below that uses matplotlib to graph a line and a sine curve to see the syntax for these steps. Do you see the difference in how the numpy arrays were created for the inputs and outputs? Run both sets of code to see the result.
Note when `connecting the dots’ you need enough points to get a smooth curve.

You Try 1.8.

Change both of the above sets of code to whole number inputs from 0 to 6.
  • What happens to your line?
  • What happens to your sine curve?

You Try 1.9.

Change the above code to use arange() instead of linspace() to set up your inputs. What is the smallest step size that makes the curve look smooth?

You Try 1.10.

Change the above code to graph \(y=x^2 \) with a traditional input window like [-10,10].
You can plot more than one curve on the same axes using the same inputs but more than one set of outputs. Run the code below to graph \(y_1 = \sin(x) \) and \(y_2=\cos(x)\) on the same graph.

You Try 1.11.

Notice that if you don’t specify the inputs, pyplot uses a default set instead. Change the above code and remove the second call for the inputs X in graph.plot(). What is the default input window pyplot uses for Y2?

You Try 1.12.

Change the above code to add a third function on the same graph.

Subsection Scatter Plots in 2D

To graph a scatterplot, use the command scatter instead of plot.

You Try 1.13.

Adjust the code in any plot above to make it into a scatter plot instead.
Hint.
Replace ax.plot() with ax.scatter() in the code.
For scatter plots sometimes you get the data from an experiment instead of a formula. As long as the outputs are given as a NumPy array, either from manipulating your input array, or by creating a completely new output array, Matplotlib will still connect the dots.

Subsection Parametric Curves in 2D

In mathematics and the sciences we sometimes introduce a new parameter \(t\) and write coordinates \(x\) and \(y\) in terms of that parameter. This is common for curves that are not functions of \(x\text{,}\) like circles or ellipses, or a nice way to model motion, where the \(x\) and \(y\) coordinate location of an object is the output at each input time \(t\text{.}\) If you haven’t seen this in a Trigonometry class, or if you need a refresher, check out insert appendix stuff here. In mathematics these parametric curves or space curves are often written as a set of two parametric equations or a vector-valued function.
For example, we can graph a circle using
\begin{equation*} \vec{r}(t)=\langle \cos(t), \sin(t)\rangle \end{equation*}
or, equivalently,
\begin{align*} x \amp= \cos(t)\\ y \amp= \sin(t) \end{align*}
for values of \(t\) in \([0,2\pi]\)
Matplotlib still graphs these curves by plotting points \((x,y)\) using plot and connecting the dots, which will make it easy to generalize these curves to 3D.

You Try 1.14.

Note that the above code graphs the unit circle. Play with the above functions for \(x\) and \(y\) to see what other interesting curves you can graph.
In particular, when you have the parameter \(t\text{,}\) can you create
  • a line?
  • a different circle?
  • a parabola?

Subsection Titles and Axes Labels

You can easily add titles and label each axis using the commands set_title("title_here"), set_xlabel("label_here"), set_ylabel("label_here"). Since the code below is longer, you might need to scroll to see all of the commands.
You can also adjust the tick marks on the axes, but it takes a little more work, and there are multiple approaches.

You Try 1.15.

Search online for a way to change the tick labels in Matplotlib. Try and adjust the "Falling Body" graph to have tickmarks every quarter of a second.

Subsection Customizing

You can customize pretty much everything in each plot: colors, markers, line width and styles, etc. Below are a few examples.
The comma separated list of possible commands inside the parentheses of a function like plot() are called the arguments of the function. The functions plot and scatter can take arguments like color="color_here", linestyle="style_here", linewidth=number_here, marker="markertype_here".

Subsection Vectors in 2D

Matplotlib plots vectors using a function from pyplot called quiver, which takes an initial coordinate, followed by the vector coordinates, to draw an arrow. Since the axes of your graph are not determined by the input domain of a function, you need to explicitly choose your axes limits using xlim and ylim.

You Try 1.16.

Try various viewing windows in the above code. What do you notice about the size of your arrow?
Since quiver is typically used for vector fields, the size scales automatically based on other elements of the graph. Here we want to use the \(xy\)-axes as a fixed scale to draw the vectors, and so will include the arguments angles='xy', scale_units='xy', scale=1 inside quiver.

You Try 1.17.

Try various vectors and viewing windows in the above code.
For multiple vectors it can be helpful to color code and use pyplot’s grid() and legend() feature.

You Try 1.18.

Try various vectors and viewing windows in the above code. Also add a horizontal and vertical axis at \(x=0\) and \(y=0\) using the code found in the second Customizing example.

Subsection Multiple plots in the same figure

Sometimes we want more than one graph in the same figure. Multiple graphs can be added to the same figure using plt.subplots(), which sets up the number of rows or columns of desired plots. Note the axes() function creates each separate graph and their individual axes.
There are other ways to set up your figure and your axes in Matplotlib. Some are shortcuts and Matplotlib will use default settings (e.g. if we do not explicitly give inputs for the function we want to graph). The approach in this section is very explicit and object oriented, which makes it easier to see how to control each feature as we get started.

Summary.

  • Every graph needs a figure object and an axes object (which is essentially a single plot). The graph object will plot just the axes if no other information is given.
  • We graph a connected curve on our axes using axes_name.plot(array x,array y) for both standard equations and parametric curves.
  • We graph a scatterplot on our axes using axes_name.scatter(array x, array y).
  • We graph a parametric curve on our axes using axes_name.plot(array x, array y).
  • We can use numpy.linspace() to efficiently create enough points for plot() to connect the dots into a smooth-looking curve.
  • We can add titles and labels using axes_name.set_title("Title") or axes_name.set_xlabel("input_label").
  • We can customize color, linestyles, plotting styles, thickness, tickmarks, font sizes, etc. to make our graph exactly what we need for publication.
  • We can specify a viewing window using arguments xlim and ylim inside axes_name.set() and graph vectors using axes_name.quiver.

Exercises Exercises

1.

Plot two different parametric curves on the same axes. Your graph should include a title, labelled axes and a legend.

2.

Find a data set with real context and at least 10 values. Plot a scatterplot of the data and the linear regression of the data set. You don’t have to use Python to find the regression, but you can if you want. Your graph should include a title, labelled axes and a legend.

3.

Create a figure with two subplots, one visualizing a vector sum, the other visualizing a vector difference. Your graphs should include titles and legends.