Tuesday, December 31, 2019

Plotting the sine function

Let’s plot the sine function over the interval from 0 to 4 . The main plotting function plot in matplotlib
does not plot functions per se, it plots (x;y) data sets. As we shall see, we can instruct the function plot either to just draw points or dots at each data point, or we can instruct it to draw straight lines between the data points. To create the illusion of the smooth function that the sine function is, we need to create enough (x;y) data points so that when plot draws straight lines between the data points, the function appears to be smooth.

The sine function undergoes two full oscillations with two maxima and two minima between 0 and 4 . So let’s start by creating an array with 33 data points between 0 and 4 , and then let matplotlib draw a straight line between them. Our code consists of four parts:

• Import the NumPy and matplotlib modules.
• Create the (x;y) data arrays.
• Have plot draw straight lines between the (x;y) data points.
• Display the plot in a figure window using the show function.

See the following program:


import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 4.*np.pi, 33)
y = np.sin(x)
plt.plot(x, y)
plt.show()


The output is shown below. It consists of the sine function plotted over the interval from 0 to 4 , as advertised, as well as axes annotated with nice whole numbers over the appropriate interval.

One problem, however, is that while the plot oscillates like a sine wave, it is not smooth (look at the peaks). This is because we did not create the (x;y) arrays with enough data points. To correct this, we
need more data points which can be created using the same program shown above but with 129 (x;y) data points instead of 33. In the above program just replace 33 in line 3 with 129 (a few more or less is ok) so that the function linspace creates an array with 129 data points instead of 33. The output iss shown below:

In making this plot, matplotlib has made a number of choices, such as the size of the figure, the color of the line, even the fact that by default a line is drawn between successive data points in the (x;y) arrays. All of these choices can be changed by explicitly instructing matplotlib to do so. This involves including more arguments in the function calls we have used and using new functions that control other properties of the plot. See the previous posts and try a few of the simpler embellishments that are possible.


Share:

0 comments:

Post a Comment