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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15858192/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 21:11:58  来源:igfitidea点击:

How to set xlim and ylim for a subplot in matplotlib

pythonmatplotlibplot

提问by Cupitor

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!

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

采纳答案by tacaswell

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

您应该使用 OO 接口到 matplotlib,而不是状态机接口。几乎所有的plt.*功能都是薄包装,基本上可以做gca().*

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

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

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)