triplebig
triplebig

Reputation: 432

Python not setting range correctly in plots

One of the most frustrating things is when you follow a tutorial on a book, and it doesn't work the way it should. I have little idea as to why this is not working. I'm using IPython right now to make my plots. I have this code:

from __future__ import division
fig,ax =subplots()
f=1.0# Hz, signal frequency
fs = 5.0 # Hz, sampling rate (ie. >= 2*f)
t= arange(-1,1+1/fs,1/fs) # sample interval, symmetric
# for convenience later
x= sin(2*pi*f*t)
ax.plot(t,x,'o-' )
ax.set_xlabel('Time' ,fontsize=18)
ax.set_ylabel(' Amplitude' ,fontsize=18)

Which gives the following graph:

enter image description here

Which is the graph expected in the book. But then when I add this additional code:

fig,ax = subplots()
ax.plot(t,x,'o-')
ax.plot(xmin = 1/(4*f)-1/fs*3,
        xmax = 1/(4*f)+1/fs*3,
        ymin = 0,
        ymax = 1.1 )
ax.set_xlabel('Time',fontsize =18)
ax.set_ylabel('Amplitude',fontsize = 18)

And I get the same graph, even though I'm setting the graph range. I've tried doing it parameter by parameter, as I found in another question - ax.ymin = 0, ax.ymax = 1.1 , etc....

Why is this happening, and what can I do to view the "zoomed in" graph?

Upvotes: 2

Views: 1372

Answers (1)

joaquin
joaquin

Reputation: 85653

To set limits to the axes you may want to use ax.set_xlim and ax.set_ylim.

fig, ax = subplots()
ax.plot(t, x, 'o-')
ax.set_xlim(1/(4*f)-1/fs*3, 1/(4*f)+1/fs*3)
ax.set_ylim(0, 1.1)
ax.set_xlabel('Time',fontsize =18)
ax.set_ylabel('Amplitude',fontsize = 18)

Afaik, ax.plot() doesn't have xmin, etc keyword arguments, so that they pass unnoticed to the plot method. What you see is the result from the previous plot ax.plot(t,x,'o-').


A second method to set limits, the one in the link you indicate, is plt.axis() .

axis(*v, **kwargs)
Convenience method to get or set axis properties.

Calling with no arguments::

  >>> axis()

returns the current axes limits ``[xmin, xmax, ymin, ymax]``.::

  >>> axis(v)

sets the min and max of the x and y axes, with
``v = [xmin, xmax, ymin, ymax]``.::

axis set both axis at the same time. see docstring for more information.

Upvotes: 3

Related Questions