We are going to plot and show the trigonometry functions sine and cosine in Python. We'll start by importing matplotlib and numpy in our code using the standard lines.
In this post, we are going to plot a couple of trigonometric functions using Python and matplotlib. Matplotlib is a library that is used to produce line plots, bar graphs, and many other types of plots. You will need to install matplotlib and NumPy with pip on the command line if they are not present in your library. Matplotlib is not included in the standard library.
Plots can reveal the data and outliers and with this, we can visually communicate with our engineers and supervisors. You will need to use the NumPy library to access the sine and cosine functions. You will also need to use the matplotlib library to draw the curve.
import matplotlib.pyplot as plt
import numpy as np
Now we will build a set of x values from zero to 4π to use in our plot. The x-values are stored in a numpy array. We have to pass there a parameter in the np.arange : start, stop, and step. We started at zero, stopped at 4π and step by 0.1 radians. Then we define a variable y
as the sine of x using numpy's sin()
function.
x = np.arange(0,4*np.pi,0.1) y = np.sin(x)
plt.plot(x,y)
plt.show()
Now for the cosine graph, the code below can be used. The explanation is the same as sine.
x = np.arange(0,4*np.pi,0.1)
y = np.cos(x)
plt.plot(x,y)
plt.show()
Both the functions can be a plot on the same graph for comparison use this code.
x = np.arange(0,4*np.pi,0.1) y = np.sin(x) z = np.cos(x) plt.plot(x,y,x,z) plt.show()
Submitted by Radhika Talwar (radhikatalwar62)
Download packets of source code on Coders Packet
Comments