如何在matplotlib中为子图设置xlim和ylim [英] How to set xlim and ylim for a subplot in matplotlib

查看:468
本文介绍了如何在matplotlib中为子图设置xlim和ylim的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想限制matplotlib中的X轴和Y轴,但要指定一个特定的子图.我所看到的 子图图本身没有任何axis属性.例如,我只想更改第二个图的极限!

I would like to limit the X and Y axis in matplotlib but for a speific subplot. As I can see subplot figure itself doesn't have any axis property. I want for example to change only the limits for the second plot!

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().*.

You should use the OO interface to matplotlib, rather than the state machine interface. Almost all of the plt.* function are thin wrappers that basically do gca().*.

plt.subplot 返回

plt.subplot returns an axes object. Once you have a reference to the axes object you can plot directly to it, change its limits, etc.

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])

,依此类推,直到您想要的任意数量的轴.

and so on for as many axes as you want.

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

or better, wrap it all up in a loop:

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)

这篇关于如何在matplotlib中为子图设置xlim和ylim的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆