我想限制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使用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])
等等,你想要多少轴都可以
或者更好的是,将它们全部封装在一个循环中:
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)