Matplotlib 如何在不扩展轴限制的情况下绘图?

Matplotlib 如何在不扩展轴限制的情况下绘图?,matplotlib,Matplotlib,我试图在现有轴上绘制,而不扩展或修改其限制 例如: import numpy as np import matplotlib.pyplot as plt xy = np.random.randn(100, 2) plt.scatter(xy[:,0], xy[:,1]) 使用拟合良好的轴限制进行精细绘图 然而,当我试图在上面画一条线时: xlim = plt.gca().get_xlim() plt.plot(xlim, xlim, 'k--') 轴限制被扩展,可能是为了在新数据周围创建

我试图在现有轴上绘制,而不扩展或修改其限制

例如:

import numpy as np
import matplotlib.pyplot as plt

xy = np.random.randn(100, 2)

plt.scatter(xy[:,0], xy[:,1])
使用拟合良好的轴限制进行精细绘图

然而,当我试图在上面画一条线时:

xlim = plt.gca().get_xlim()
plt.plot(xlim, xlim, 'k--')
轴限制被扩展,可能是为了在新数据周围创建填充


如何在没有填充的情况下绘制直线?

一个强力解决方案是在绘制之前跟踪轴限制,然后在绘制之后重置它们

像这样:

from contextlib import contextmanager

@contextmanager
def preserve_limits(ax=None):
    """ Plot without modifying axis limits """
    if ax is None:
        ax = plt.gca()

    xlim = ax.get_xlim()
    ylim = ax.get_ylim()

    try:
        yield ax
    finally:
        ax.set_xlim(xlim)
        ax.set_ylim(ylim)
现在比较

plt.scatter(xy[:,0], xy[:,1])

xlim = plt.gca().get_xlim()
plt.plot(xlim, xlim, 'k--')

您可以使用:

根据文件:

将轴视图自动缩放到数据(切换)

简单轴视图自动缩放的简便方法。它打开或关闭自动缩放,然后,如果任一轴的自动缩放处于打开状态,它将在指定的一个或多个轴上执行自动缩放。 参数:

enable : bool or None, optional
         True (default) turns autoscaling on, False turns it off. None leaves the autoscaling state unchanged.
axis : {'both', 'x', 'y'}, optional
       which axis to operate on; default is 'both'
tight: bool or None, optional
       If True, set view limits to data limits; if False, let the locator
       and margins expand the view limits; if None, use tight scaling
       if the only artist is an image, otherwise treat tight as False.
       The tight setting is retained for future autoscaling until it is
       explicitly changed.

如果单独设置x轴限制,则在更改它们之前,不会覆盖它们,无论打印的是什么。要使其与代码相匹配,请尝试:

plt.xlim(xlim)

当你得到xlim时,它会得到当前的限制,但是一旦你“设置”了它们,它们就会被锁定,直到你再次更改它们。这也适用于y轴,如果您希望这些轴也被固定(只需将“x”替换为“y”并添加代码)。

设置
plt。自动缩放(False)
可防止发生自动缩放

import numpy as np; np.random.seed(42)
import matplotlib.pyplot as plt

xy = np.random.randn(100, 2)
# By default plots are autoscaled. 
plt.scatter(xy[:,0], xy[:,1])

#Turn autoscaling off
plt.autoscale(False)
xlim = plt.gca().get_xlim()
plt.plot(xlim, xlim, 'k--')

plt.show()

设置
tight=True
是否会“反向”拧紧轴缩放?我喜欢初始非紧自动缩放,但我希望自动缩放仅在绘制直线时变紧。它看起来也可以使用轴。这里的自动缩放视图,但我不确定我是否刚刚选中
tight=True
似乎具有追溯性,而
enabled=False
则不具有追溯性。@shadowtalker仅设置
tight=True
可使自动缩放保持启用状态,依此类推,每个新绘图都会更改限制以适应所有数据,而
enabled=False
则完全禁用缩放,从而使限制保持不变。这就是答案。不幸的是,
tight=True
似乎具有“追溯性”,扰乱了已绘制数据的比例。而
enabled=False
似乎不会撤消初始自动缩放。否,自动缩放不具有追溯性。它将涉及设置后打印的所有内容。在这种情况下,matplotlib中似乎存在错误。看看如果在代码中编写
plt.autoscale(tight=True)
而不是
plt.autoscale(False)
,会发生什么。它实际上改变了散射点周围的比例。这是意料之中的,对吗?因为默认情况下,
enable
为True。也许我没有完全理解你想要达到的目标。我的观点是这种行为是不一致的。一个参数具有追溯性,另一个参数不具有追溯性。似乎设置初始缩放可能是一种特殊情况。
fig, ax = plt.subplots()
ax.plot(np.random.normal(size=(100,)),np.random.normal(size=(100,)),'bo')
ax.autoscale(tight=True)
xlim = ax.get_xlim()
plt.plot(xlim, xlim, 'k--')
plt.xlim(xlim)
import numpy as np; np.random.seed(42)
import matplotlib.pyplot as plt

xy = np.random.randn(100, 2)
# By default plots are autoscaled. 
plt.scatter(xy[:,0], xy[:,1])

#Turn autoscaling off
plt.autoscale(False)
xlim = plt.gca().get_xlim()
plt.plot(xlim, xlim, 'k--')

plt.show()