Skip to content
Home » matplotlib Part 7 – Axis Range

matplotlib Part 7 – Axis Range

Spread the love

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]:
[<matplotlib.lines.Line2D at 0x222eaa55048>]

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]:
(-5, 5)
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]:
(-0.2, 0.2)
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]:
(-1, 3)

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.

Here’s the video version of this article:


Spread the love

Leave a Reply