I was trying to create a sinewave graph using Matplotlib for the parameters given as below.
Create a figure of size 12 inches in width, and 3 inches in height. Name it as fig.
Create an axis, associated with figure fig, using add_subplot. Name it as ax.
Create a numpy array t with 200 values between 0.0 and 2.0. Use the 'linspace' method to generate 200 values.
Create a numpy array v, such that v = np.sin(2.5np.pit).
Pass t and v as variables to plot function and draw a red line passing through the selected 200 points. Label the line as sin(t).
Label X-Axis as Time (seconds).
Label Y-Axis as Voltage (mV).
Set Title as Sine Wave.
Limit data on X-Axis from 0 to 2.
Limit data on Y-Axis from -1 to 1.
Mark major ticks on X-Axis at 0, 0.2, 0.4, 0.6, 0.8, 1.0, 1.2, 1.4, 1.6, 1.8, and 2.0.
Mark major ticks on Y-Axis at -1, 0, and 1.
Add a grid, whose linestyle is '--'.
Add a legend.
Wrote the below and it almost came as required, but the expected graph is slightly different to what i write. I did gave the x and y limits but the graph seems to be taking further than that.
import numpy as np
import matplotlib.ticker as ticker
fig = plt.figure(figsize=(12,3))
ax = fig.add_subplot(111)
t = np.linspace(0.0,2.0,200)
v = np.sin(2.5*np.pi*t)
ax.set(title='Sine Wave', xlabel='time (seconds)', ylabel='Voltage (mV)', xlim = (0,2), ylim=(-1,1))
xmajor = [0, 0.2, 0.4, 0.6, 0.8, 1.0, 1.2, 1.4, 1.6, 1.8, 2.0]
ymajor = [-1,0,1]
ax.xaxis.set_major_formatter(ticker.FixedFormatter(xmajor))
ax.yaxis.set_major_formatter(ticker.FixedFormatter(ymajor))
plt.plot(t, v, label='sin(t)',color = 'red')
plt.legend()
plt.rc('grid', linestyle='--', color='black')
plt.grid(True)
plt.show()
couple of points here
- The axis is not limiting to what i provided
- the grid seems to be different.
Any ideas how to fix this please.


