如何在matplotlib中设置子批次的xlim和ylim

2024-03-28 02:18:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我想限制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()

Tags: import图形属性matplotlibasshowfigplt
1条回答
网友
1楼 · 发布于 2024-03-28 02:18:13

您应该学习一下matplotlib的OO接口,而不仅仅是状态机接口。几乎所有的plt.*函数都是薄包装,基本上都是gca().*

^{}返回一个^{}对象。一旦你有一个轴对象的参考,你可以直接打印到它,改变它的限制,等等

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)

相关问题 更多 >