如何在 Matplotlib 中设置轴的范围
Suraj Joshi
2024年2月16日
Matplotlib
Matplotlib Axes
-
xlim()和ylim()在 Matplotlib 中设置轴的限制 -
set_xlim()和set_ylim()方法来设置轴限制 -
使用
axis()方法在 Matplotlib 中设置轴的限制
为了设置 X 轴的范围限制,我们可以使用 xlim() 和 set_xlim() 方法。类似地,为 Y 轴设置范围限制,我们可以使用 ylim() 和 set_ylim() 方法。我们也可以使用 axis() 方法来控制两个轴的范围。
xlim() 和 ylim() 在 Matplotlib 中设置轴的限制
matplotlib.pyplot.xlim() 和 matplotlib.pyplot.ylim() 可用于分别设置或获取 X 轴和 Y 轴的范围限制。如果在这些方法中传递参数,则它们将设置各个轴的极限,如果不传递任何参数,则将获得各个轴的范围。
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 10, 500)
y = np.sin(2 * np.pi * x) + 1
fig = plt.figure(figsize=(8, 6))
plt.plot(x, y)
plt.title("Setting range of Axes", fontsize=25)
plt.xlabel("x", fontsize=18)
plt.ylabel("1+sinx", fontsize=18)
plt.xlim(4, 8)
plt.ylim(-0.5, 2.5)
plt.show()
输出:

这会将 X 轴的范围从 4 设置为 8,而将 Y 轴的范围从 -0.5 设置为 2.5。
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(1, 10, 500)
y = np.sin(2 * np.pi * x) + 1
fig = plt.figure(figsize=(8, 6))
plt.plot(x, y)
plt.title("Plot without limiting axes", fontsize=25)
plt.xlabel("x", fontsize=18)
plt.ylabel("1+sinx", fontsize=18)
plt.show()
输出:

从输出图中可以看出,如果不使用 xlim()和 ylim()函数,则会得到一个图,该图的整个轴范围为 X 轴,范围从 0 到 10,而 Y 轴的范围从 0 到 2。
set_xlim() 和 set_ylim() 方法来设置轴限制
matplotlib.axes.Axes.set_xlim 和 matplotlib.axes.Axes.set_ylim 也用于设置在结果图上查看的数字范围的限制。
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 10, 500)
y = np.sin(2 * np.pi * x) + 1
fig = plt.figure(figsize=(8, 6))
axes = plt.axes()
axes.set_xlim([4, 8])
axes.set_ylim([-0.5, 2.5])
plt.plot(x, y)
plt.title("Setting range of Axes", fontsize=25)
plt.xlabel("x", fontsize=18)
plt.ylabel("1+sinx", fontsize=18)
plt.show()
输出:

使用 axis() 方法在 Matplotlib 中设置轴的限制
我们还可以使用 matplotlib.pyplot.axis() 来设置轴的范围限制。语法如下:
plt.axis([xmin, xmax, ymin, ymax])
该方法消除了用于控制 X 轴和 Y 轴的单独功能的需要。
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 10, 50)
y = np.sin(2 * np.pi * x) + 1
fig = plt.figure(figsize=(8, 6))
plt.axis([4, 9, -0.5, 2.5])
plt.plot(x, y)
plt.title("Setting range of Axes", fontsize=25)
plt.xlabel("x", fontsize=18)
plt.ylabel("1+sinx", fontsize=18)
plt.show()
输出:

Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
作者: Suraj Joshi
Suraj Joshi is a backend software engineer at Matrice.ai.
LinkedIn