如何在matplotlib中为子图设置xlim和ylim

Cup*_*tor 152 python plot matplotlib

我想限制matplotlib中的X和Y轴,但是对于特定的子图.我可以看到subplot图本身没有任何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()
Run Code Online (Sandbox Code Playgroud)

tac*_*ell 218

你应该学习matplotlib的一些OO接口,而不仅仅是状态机接口.几乎所有的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])
Run Code Online (Sandbox Code Playgroud)

等等,可以根据需要设置多个轴.

或者更好,将它全部包装在一个循环中:

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)
Run Code Online (Sandbox Code Playgroud)

  • 对不起,忘掉了`plt.ylim`中的那一点魔力.在`axes`上还有一个`get_ylim()`函数,它将返回限制和`ax.get_yaxis()`函数,它将返回给你`轴'(注意'axes`和`axis`之间的区别) .还有xaxis的对称版本. (12认同)
  • @dashesy你使用`set_xlim`和`set_ylim`.`plt`有许多_fewer_选项,而不是直接使用axis对象.实际上,`plt`中的几乎每个函数都是一个非常薄的包装器,首先调用`ax = plt.gca()`然后调用该对象上的函数.除了交互式工作之外,你不应该使用"plt". (7认同)
  • 保持轴实例的问题在于它没有plt具有的所有属性,例如,不能使用axis.ylim()来获取轴上的绘图的ylim. (2认同)