如何在matplotlib中为子图设置xlim和ylim [重复]


问题内容

这个问题已经在这里有了答案

Python,Matplotlib,子图:如何设置轴范围? (5个答案)

5年前关闭。

我想限制matplotlib中的X轴和Y轴用于特定的子图。子图图本身没有任何axis属性。例如,我想仅更改第二个图的限制:

import matplotlib.pyplot as plt
fig=plt.subplot(131)
plt.scatter([1,2],[3,4])
fig=plt.subplot(132)
plt.scatter([10,20],[30,40])
fig=plt.subplot(133)
plt.scatter([15,23],[35,43])
plt.show()

问题答案:

您应该将OO接口用于matplotlib,而不是状态机接口。几乎所有plt.*功能都是基本上可以完成的薄包装器gca().*

plt.subplot返回一个axes对象。一旦有了轴对象的引用,就可以直接对其进行绘制,更改其限制等。

import matplotlib.pyplot as plt

ax1 = plt.subplot(131)
ax1.scatter([1, 2], [3, 4])
ax1.set_xlim([0, 5])
ax1.set_ylim([0, 5])


ax2 = plt.subplot(132)
ax2.scatter([1, 2],[3, 4])
ax2.set_xlim([0, 5])
ax2.set_ylim([0, 5])

依此类推,可以选择任意数量的轴。

或更妙的是,将它们包装成一个循环:

import matplotlib.pyplot as plt

DATA_x = ([1, 2],
          [2, 3],
          [3, 4])

DATA_y = DATA_x[::-1]

XLIMS = [[0, 10]] * 3
YLIMS = [[0, 10]] * 3

for j, (x, y, xlim, ylim) in enumerate(zip(DATA_x, DATA_y, XLIMS, YLIMS)):
    ax = plt.subplot(1, 3, j + 1)
    ax.scatter(x, y)
    ax.set_xlim(xlim)
    ax.set_ylim(ylim)