Python Program to Plot Sine Function Using Numpy & Matplotlib

To plot sine wave in python, we use NumPy library and Matplotlib library.

NumPy is the fundamental package for scientific computing with Python. Matplotlib is a Python 2D plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments across platforms.

In this python program we use NumPy to generate time values and calculate sin(time) for sine data. And Matplotlib is used to handle plotting data and configuring plot attributes like label, grid etc.

Python Source Code: Sine Function

# Importing Required Libraries
import numpy as np
import matplotlib.pyplot as plt

# Generating time data using arange function from numpy
time = np.arange(-3*np.pi, 3*np.pi, 0.01)

# Finding amplitude at each time
amplitude = np.sin(time)

# Plotting time vs amplitude using plot function from pyplot
plt.plot(time, amplitude)

# Settng title for the plot in blue color
plt.title('Sine Wave', color='b')

# Setting x axis label for the plot
plt.xlabel('Time'+ r'$\rightarrow$')

# Setting y axis label for the plot
plt.ylabel('Sin(time) '+ r'$\rightarrow$')

# Showing grid

# Highlighting axis at x=0 and y=0
plt.axhline(y=0, color='k')
plt.axvline(x=0, color='k')

# Finally displaying the plot

Sine Wave Output

Sine Wave Using Python Output
Figure: Sine Wave Using Python Output

Python Sine Wave: Exaplanation (Step Wise)

  1. Step 1: Importing Libraries Code import numpy as np and import matplotlib.pyplot as plt are used to import numpy and matplotlib.pyplot Library.
  2. Step 2: Generating Time Data Code time = np.arange(-3*np.pi, 3*np.pi, 0.01) is used to generate data form -3*π to 3*π in equal interval of 0.01. Function arange() is defined in numpy.
  3. Step 3: Generating Amplitude Data Code amplitude = np.sin(time) is used to calculate sine value at each generated time data. Function sin() is also defined in numpy.
  4. Step 4: Plotting Code plt.plot(time, amplitude) is used to plot generated data of time and amplitude. Here time is x-axis data and amplitude is y-axis data.
  5. Step 5: Setting Title Code plt.title('Sine Wave', color='b') is used to set title of the generated figure in blue color. color='b' indicates title is in Blue Color.
  6. Step 6: Setting Labels Code plt.xlabel('Time'+ r'$\rightarrow$') and plt.ylabel('Sin(time) '+ r'$\rightarrow$') are used to set labels for x-axis and y-axis. Here r'$\rightarrow$ is used to generate right arrow → which is concatenated with Time and Amplitude using + operator.
  7. Step 7: Showing Grids in Figure Code plt.grid() is used to display grid in generated plot.
  8. Step 8: Highlighting Origin Line Code plt.axhline(y=0, color='k') and plt.axvline(x=0, color='k') are used to high light x=0 line and y=0 line in generated plot.
  9. Step 9: Finally Displaying Figure Code is used to display final plot in output.