在matplotlib中创建方形子图(高度和宽度相等)

got*_*nes 23 python matplotlib

当我运行此代码时

from pylab import *

figure()
ax1 = subplot(121)
plot([1, 2, 3], [1, 2, 3])
subplot(122, sharex=ax1, sharey=ax1)
plot([1, 2, 3], [1, 2, 3])
draw()
show()
Run Code Online (Sandbox Code Playgroud)

我得到两个在X维度上"压扁"的子图.对于两个子图,如何获得这些子图,使得Y轴的高度等于X轴的宽度?

我在Ubuntu 10.04上使用matplotlib v.0.99.1.2.

更新2010-07-08:让我们看看一些不起作用的东西.

谷歌搜索了一整天后,我认为它可能与自动缩放有关.所以我试着摆弄它.

from pylab import *

figure()
ax1 = subplot(121, autoscale_on=False)
plot([1, 2, 3], [1, 2, 3])
subplot(122, sharex=ax1, sharey=ax1)
plot([1, 2, 3], [1, 2, 3])
draw()
show()
Run Code Online (Sandbox Code Playgroud)

matplotlib坚持自动缩放.

from pylab import *

figure()
ax1 = subplot(121, autoscale_on=False)
plot([1, 2, 3], [1, 2, 3])
subplot(122, sharex=ax1, sharey=ax1, autoscale_on=False)
plot([1, 2, 3], [1, 2, 3])
draw()
show()
Run Code Online (Sandbox Code Playgroud)

在这一个中,数据完全消失.WTF,matplotlib?只是WTF?

好的,也许我们可以修正宽高比吗?

from pylab import *

figure()
ax1 = subplot(121, autoscale_on=False)
plot([1, 2, 3], [1, 2, 3])
axes().set_aspect('equal')
subplot(122, sharex=ax1, sharey=ax1)
plot([1, 2, 3], [1, 2, 3])
draw()
show()
Run Code Online (Sandbox Code Playgroud)

这个导致第一个子图完全消失.那真好笑!谁想出那个?

严肃地说,现在......这真的是一件难以实现的事吗?

Joe*_*ton 21

当您使用sharex和sharey时,您在设置图表方面的问题就出现了.

一种解决方法是不使用共享轴.例如,您可以这样做:

from pylab import *

figure()
subplot(121, aspect='equal')
plot([1, 2, 3], [1, 2, 3])
subplot(122, aspect='equal')
plot([1, 2, 3], [1, 2, 3])
show()
Run Code Online (Sandbox Code Playgroud)

但是,一个更好的解决方法是更改​​"可调"keywarg ......你想要adjust ='box',但是当你使用共享轴时,它必须是可调='datalim'(并将其设置回'box' '给出错误).

但是,还有第三种选择adjustable来处理这种情况:adjustable="box-forced".

例如:

from pylab import *

figure()
ax1 = subplot(121, aspect='equal', adjustable='box-forced')
plot([1, 2, 3], [1, 2, 3])
subplot(122, aspect='equal', adjustable='box-forced', sharex=ax1, sharey=ax1)
plot([1, 2, 3], [1, 2, 3])
show()
Run Code Online (Sandbox Code Playgroud)

或者更现代的风格(注意:这部分答案在2010年不起作用):

import matplotlib.pyplot as plt

fig, axes = plt.subplots(ncols=2, sharex=True, sharey=True)
for ax in axes:
    ax.plot([1, 2, 3], [1, 2, 3])
    ax.set(adjustable='box-forced', aspect='equal')

plt.show()
Run Code Online (Sandbox Code Playgroud)

无论哪种方式,你都会得到类似的东西:

在此输入图像描述

  • `box-forced` 不起作用,`box` 起作用了。我使用的是 2.1.0 版。 (5认同)