Menu Close

Plotting Trigonometric Functions in Python – NumPy and Matplotlib

Python Programming
To plot a trigonometric function in Python, you can use the NumPy and Matplotlib libraries. Here’s an example of how to plot the sine function:  
					import numpy as np
import matplotlib.pyplot as plt

# Generate data for x values
x = np.linspace(0, 2*np.pi, 100)

# Calculate y values for sine function
y = np.sin(x)

# Plot the sine function
plt.plot(x, y)

# Add title and axis labels
plt.title("Sine Function")

# Display the plot



In this example,

  • we first generate 100 evenly spaced x values between 0 and 2π using the linspace function from NumPy.
  • Then we calculate the y values for the sine function using NumPy’s sin function.
  • Next, we use Matplotlib’s plot function to create a line plot of the sine function.
  • We then add a title and axis labels using the title, xlabel, and ylabel functions. Finally, we display the plot using the show function.

To Generate Other Plots (cos, tan etc.)

You can modify this example to plot other trigonometric functions such as cosine or tangent by replacing the np.sin function with np.cos or np.tan, respectively.

More Related Stuff