在matplotlib中创建等高等宽的正方形子块

2024-05-16 22:33:42 发布

您现在位置:Python中文网/ 问答频道 /正文

当我运行此代码时

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

我得到了两个在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()

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

在这个例子中,数据完全消失了。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()

这个导致第一个子块完全消失。太搞笑了!谁想到的那个?

说真的,现在。。。这真的是一件很难完成的事情吗?


Tags: fromimportfalseplotonshow子块figure
2条回答

试试看:

from pylab import *

figure()
ax1 = subplot(121, autoscale_on=False, aspect='equal', xlim=[1,3], ylim=[1,3])
plot([1, 2, 3], [1, 2, 3])
##axes().set_aspect('equal')
ax2 = subplot(122, autoscale_on=False, aspect='equal', xlim=[1,3], ylim=[1,3])
plot([1, 2, 3], [1, 2, 3])
draw()
show()

我注释掉了axes()行,因为这将在任意位置创建一个新的axes,而不是具有计算位置的预制subplot

调用subplot实际上会创建Axes实例,这意味着它可以使用与Axes相同的属性。

我希望这有帮助:)

当您使用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()

然而,一个更好的解决办法是改变“可调”的关键。。。您需要可调的'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()

或者用更现代的方式(注:这部分答案在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()

不管怎样,你都会得到类似的东西:

enter image description here

相关问题 更多 >