How it works…

We start by generating the data to be plotted, with the three following statements:

xvalues = np.linspace(-np.pi, np.pi, 300)
yvalues1 = np.sin(xvalues)
yvalues2 = np.cos(xvalues)

We first create an xvalues array, containing 300 equally spaced values between -π and π. We then compute the sine and cosine functions of the values in xvalues, storing the results in the yvalues1 and yvalues2 arrays. Next, we generate the first line plot with the following statement:

plt.plot(xvalues, yvalues1, 
lw=2, color='red',
label='sin(x)')

The arguments to the plot() function are described as follows:

  • xvalues and yvalues1 are arrays containing, respectively, the x and y coordinates of the points to be plotted. These arrays must have the same length.
  • The remaining arguments are formatting options. lw specifies the line width and color the line color. The label argument is used by the legend() function, discussed as follows.

The next line of code generates the second line plot and is similar to the one explained previously. After the line plots are defined, we set the title for the plot and the legends for the axes with the following commands:

plt.title('Trigonometric Functions')
plt.xlabel('x')
plt.ylabel('sin(x), cos(x)')

We now generate axis lines with the following statements:

plt.axhline(0, lw=0.5, color='black')
plt.axvline(0, lw=0.5, color='black')

The first arguments in axhline() and axvline() are the locations of the axis lines and the options specify the line width and color.

We then add a legend for the plot with the following statement:

plt.legend()

Matplotlib tries to place the legend intelligently, so that it does not interfere with the plot. In the legend, one item is being generated by each call to the plot() function and the text for each legend is specified in the label option of the plot() function.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset