VSEC201 Programming Skills in Python Language
Assignment No. 9
Statement: Plot sin(x) and cos(x) functions for values of x between 0 and pi. Use
inbuilt libraries numpy and matplotlib.
Theory:
NumPy is short for "Numerical Python".
NumPy is used for working with arrays. In Python, lists serve the purpose of arrays,
but they are slow to process. NumPy aims to provide an array object that is up to 50
x faster than traditional Python lists.
matplotlib.pyplot is a collection of functions that make matplotlib work like MATLAB.
Each pyplot function makes some change to a figure: e.g., creates a figure, creates a
plotting area in a figure, plots some lines in a plotting area, decorates the plot with
labels, title, legends etc.
#Sourcecode:
# Import the matplotlib and numpy library
#----------------------------------------------------------------------------
import matplotlib.pyplot as plt
import numpy as np
#----------------------------------------------------------------------------
# For X-axis settings
x=np.arange(0, np.pi, 0.1)
# Alternative way of x-axis setting
#np.linspace(start, stop, num=50 (Samples to generate, defauult=50))
#x=np.linspace(0,10,200)
#----------------------------------------------------------------------------
# Define the functions
y=np.sin(x)
z=np.cos(x)
#----------------------------------------------------------------------------
# Plotting the x,y and x,z functions using .plot
plt.plot(x,y,color='blue', linestyle='solid', linewidth =2, marker='o', markersize =5 )
plt.plot(x,z,color='red', linestyle='solid', linewidth =2, marker='o', markersize =5 )
#----------------------------------------------------------------------------
# Define the x and y axis labels
plt.xlabel("x values from zero to pi")
plt.ylabel("sin(x) and cos(x)")
#----------------------------------------------------------------------------
# Define the title of the plot
plt.title("Plot of six(x) and cos(x) from zero to pi")
#----------------------------------------------------------------------------
# Define the legends
plt.legend(["sin(X)", "cos(x)"])
plt.show()
Output: