In this part of the Matplotlib series we’ll be talking about axis ranges. Let’s start by plotting a function:
In [1]:
%matplotlib inline
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-10, 10, 100)
y = np.sin(x) / x
fig, ax = plt.subplots()
ax.plot(x, y)
Out[1]:
X AND Y AXIS LIMITS
As you can see, the axis ranges are adjusted for us automatically to fit the data: from -10.0 to 10.0 on the X axis and from -0.2 to 1.0 on the Y axis. But we can explicitly set the axis ranges for each axis using the set_xlim and set_ylim methods respectively. You pass the lower and upper limit to either method. Have a look:
In [2]:
fig, ax = plt.subplots()
ax.plot(x, y)
# The X range should be from -5 to 5 because we're only interested in the middle part of the graph.
ax.set_xlim(-5, 5)
Out[2]:
In [3]:
fig, ax = plt.subplots()
ax.plot(x, y)
# And now the Y range should be from -0.2 to 0.2 because we're only interested in the lower part of the graph.
ax.set_ylim(-0.2, 0.2)
Out[3]:
In [4]:
fig, ax = plt.subplots()
ax.plot(x, y)
# This time we'll set both X and Y axis limits so that the graph is smaller in size.
ax.set_xlim(-15, 15)
ax.set_ylim(-1, 3)
Out[4]:
Here’s the video version of this article: