How to Draw a Figure
In this lesson, we will learn how to draw a line on a canvas by using the function subplot().
We'll cover the following
Let’s draw our first figure by following a step-by-step process. This process will teach us how to draw a figure using the formal method. In this figure, we will draw two lines. Each will be generated from a defined number, obtained by using numpy
.
Step 1 - Create a dataset
We will start by creating our dataset, which will consist of two lines. In this example, we will use numpy
to generate a series of points on the x-axis. Then, we will use sin
to generate a corresponding series of points on the y-axis.
import numpy as np
points = np.linspace(-5, 5, 256)
y1 = np.power(points, 3) + 2.0
y2 = np.sin(points) - 1.0
Step 2 - Create a canvas
We will then create a canvas with only one axis. The function subplots()
helps us create a figure, or canvas, with a specified layout. If we don’t pass the nrows
or ncols
parameters, subplots()
will create a canvas with only one axes.
import matplotlib.pyplot as plt
fig, axe = plt.subplots()
Step 3 - Add data to the axes
Next, we will add data to the axes by using plot
. By default, the first argument is for the x-axis, and the second argument is for the y-axis.
axe.plot(points, y1)
axe.plot(points, y2)
Step 4 - Show the figure
We can show our figure by calling plt.show()
.
Notice: The
plt
here is a reference tomatplotlib.pyplot
.
plt.show()
NOTICE: The code above is different from the code below. On a PC, we can call
plt.show()
to display an image on the screen. However, in the example code below, we need to output the image as a file.