Noob coder
Noob coder

Reputation: 55

Grid and limit issues with Matplotlib

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()

My plot and expected: Attached my plot and expected

couple of points here

  1. The axis is not limiting to what i provided
  2. the grid seems to be different.

Any ideas how to fix this please.

Updated Picture: Updated Picture

Upvotes: 1

Views: 2282

Answers (1)

Roim
Roim

Reputation: 3066

Your problem is with ticker.FixedFormatter. First, consider this solution:

import numpy as np
import matplotlib.ticker as ticker
import matplotlib.pyplot as plt
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))
plt.xticks([0, 0.2, 0.4, 0.6, 0.8, 1.0, 1.2, 1.4, 1.6, 1.8, 2.0])
plt.yticks([-1, 0, 1])
plt.plot(t, v, label='sin(t)',color = 'red')
plt.legend()
ax.grid(color='black', linestyle='--', dashes=[8, 6], alpha=0.5)
plt.grid(True)

plt.show()

which results the following graph:

results

Notice I changed ax.xaxis.set_major_formatter to plt.xticks which allows you directly to manipulate xticks.

You used FixedFormatter, which means the ticks location are fixed and you just name them - that's why the first 3 ticks on yaxis where -1, 0, 1 (your input), regardless of what their values was. Unless you have a good reason to use matplotlib.ticker (aka set locations of ticks or format them) I recommend to use simple plt.xticks to set the values of them.

Second change was to directly control the grid by using ax.grid instead of drawing a rectangle, which I believe is more correct. As you were pretty specific in your request on the dashed line (default "--" is different then what you ask for) I added dashed=[float, float] param. It allows you control the size of the dashes - you can maniputlate them as desired. The alpha param was added to give it more 'greyish' style but you can remove it

Upvotes: 2

Related Questions