如何使收缩/扩展以实现纵横比与 twinx/twiny 一致?

问题描述 投票:0回答:1

当我使用Python库

twinx
添加
twiny
和/或
matplotlib
轴时,指定长宽比的效果变得不一致:

  • 当我设置没有
    twinx
    /
    twiny
    的宽高比时,轴会放大(范围缩小)以实现所需的宽高比
  • 当我添加
    twinx
    和/或
    twiny
    轴时,结果取决于我添加
    twinx
    twiny
    的顺序,以及是否需要缩小 x 轴或 y 轴。

下面是不一致行为的示例(左轴和右轴显示不同的限制)。 当双轴添加为

axes[1].twinx().twiny()
x 或增加 y 范围时,它将再次保持一致。

当我想预测我的代码会做什么时,这让我有些头痛,而这恰恰不是我使用 python 的目的;)

有没有办法让它的行为符合预期:即轴总是收缩,无论是否添加 twinx 和/或 twiny?

如果可以明确地在收缩/扩展行为之间进行选择,我会更高兴。有谁知道怎么办吗

非常感谢!

import matplotlib.pyplot as plt

fig, axes = plt.subplots(1, 2)
axes[1].twinx().twiny()

for ax in axes:
    ax.grid(True)
    ax.set(
        aspect=1,
        adjustable='datalim',
    )

    ax.set(
        ylim=(10, 20),  # axes are the same when this range is larger, e.g. (10, 30)
        xlim=(20, 30),
    )

    # so the output below shows the final values
    ax.apply_aspect()
    print(ax.get_xlim())
    print(ax.get_ylim())

回应 Guimute 的评论: 很好,医生说我不应该这样做。然而,matplotlib 并没有抱怨。当我将

'datalim'
更改为
'box'
时,我确实得到了
RuntimeError: Adjustable 'box' is not allowed in a twinned Axes; use 'datalim' instead
。 (所以与文档的建议相反)。

如果我将双轴添加为

axes[1].twinx()
axes[1].twiny()

两种方法都出现错误。

对 matplotlib 尝试为孪生轴提供相同数量的刻度的建议感到好奇,并且它们的限制规范应该产生影响;我在下面的示例中没有看到这种情况发生。

在我的应用程序中,我当然会使用双轴做更多事情。为了使示例简单,我省略了它,但匹配的刻度数是不可预期的。

我想到的应用程序是例如一组轴上的纬度/经度坐标,另一组轴上的北距/东距坐标。

无论如何,这是示例二:

import matplotlib.pyplot as plt

fig, axes = plt.subplots(1, 2)
twiny = axes[1].twiny()
twiny.set(xlim=(0, .8))

for ax in axes:
    ax.grid(True)
    ax.set(
        aspect=1,
        adjustable='datalim',
    )

    ax.set(
        ylim=(10, 30),
        xlim=(20, 30),
    )

    ax.apply_aspect()

结果:

也许

twinx
/
twiny
不适用于此应用程序,但我对得到的结果感到惊讶。

python matplotlib aspect-ratio twinx twiny
1个回答
0
投票

并不是真正的解释,但现在我将首先完成原始轴的工作,然后添加双胞胎。这样至少行为是可以预测的。

© www.soinside.com 2019 - 2024. All rights reserved.