In the previous part of the Matplotlib series we created the matplotlib folder in Jupyter Notebook. Let’s add a notebook now. With Jupyter Notebook launched, first select the matplotlib folder on the left (A) and then click on New (B) and select Python 3 (C):
This will create a new notebook. To rename it click on Untitled:
When the popup window appears, go ahead and type in the new name (A). As mentioned in the previous lecture, I’m going to use a naming convention based on the number of the lecture. Then hit Rename (B).
Now you will see the new title:
And now we’re ready to create a first basic graph. First we need to import the modules that we will need. Here’s the code with comments. Just type it in into the first cell. Don’t worry if you don’t understand what’s going on, it will be all explained in the following articles.
Here’s the code:
# This magic command is only used in the IPython environment,
# so in the IPython console and in Jupyter Notebook.
# It should be used only once per session, just like the imports
# further down. If you use this command, all graphs will
# be embedded directly in the notebook rather than displayed
# in a separate window.
%matplotlib inline
# Here are the imports. Here you can also see the commonly
# used aliases for matplotlib and matplotlib.pyplot.
import matplotlib as mpl
import matplotlib.pyplot as plt
# We will also use numpy for this example.
import numpy as np
# And here's the example.
# First let's create an array of 100 evenly spaced numbers
# between -10 and 10. We can use the numpy linspace method
# to do that. These are going to be the X-coordinates.
# The method takes three parameters: the lower and upper
# range and the number of items.
x = np.linspace(-10, 10, 100)
# Now we're going to plot the following quadratic function:
# y = x ** 2 - 2 * x + 3, so we have:
y = x ** 2 - 2 * x + 3
# Now we have to generate the Figure instance and an Axes
# instance. The terms FIGURE and AXES are among the basic
# Matplotlib terms. A figure is the canvas area where one
# or more Axes instances can be added. An Axes instance is
# a region of the figure with its own individual coordinate
# system. There may be one area instance, like in the example
# below, but there may also be more.
# We can use the plt.subplots function to create a figure
# and an axis at the same time.
fig, ax = plt.subplots()
# And now let's finally plot the graph. Most functions we're
# going to use are Axes methods.
ax.plot(x, y)
# Now hit Ctrl + Enter to execute the code.
This is just a very basic graph and we should definitely add some elements to it. We’ll learn how to do it in the following parts of the series.
Here’s the video version of the article: