我希望在matplotlib中为特定的子图限制X和Y轴。子图本身没有任何轴属性。例如,我只想更改第二个图的限制:
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()
我希望在matplotlib中为特定的子图限制X和Y轴。子图本身没有任何轴属性。例如,我只想更改第二个图的限制:
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()
你应该使用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)
set_xlim
和 set_ylim
。相比直接使用轴对象,plt
的选项要少得多。事实上,plt
中的几乎每个函数都是一个非常薄的包装器,首先调用 ax = plt.gca()
,然后在该对象上调用任何函数。你不应该在除交互式工作以外的任何情况下使用 plt
。 - tacaswellplt.ylim
中的那个魔术部分。在 axes
上还有一个 get_ylim()
函数,它将返回限制范围,ax.get_yaxis()
函数将返回 axis
(请注意 axes
和 axis
之间的区别)。x轴也有对称版本。 - tacaswellplt.xlim
和 plt.ylim
位于 matplotlib.pyplot
中,而 ax.set_xlim
和 ax.set_ylim
是 Axes
对象上的方法。在几乎所有情况下,您应该优先使用 Axes
方法而不是 pyplot。 - tacaswell