2010-07-08 37 views
17

方副区(相等的高度和宽度)当我运行此代码创建在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() 

我得到两个副区它们在X维度“压扁”。对于两个子图,我如何得到这些子图使得Y轴的高度等于X轴的宽度?

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

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

经过Google整天搜索后,我认为它可能与自动缩放有关。所以我试着摆弄它。

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

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

非常认真,现在......这真的应该是一件很难完成的事情吗?

回答

16

你在设定情节方面的问题来了。当你使用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() 

然而,一个更好的解决办法是改变“可调” keywarg ......你想调节=“盒子”,但是当你使用公共坐标轴,它具有要调整='datalim'(并将其设置回“框”给出错误)。

但是,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

+0

我使用axis('equal')更多的MATLAB像synthax。当MATLAB中的方面需要像“轴平方”时,我使用figure(1,figsize =(6,6))。 – otterb 2013-02-07 00:28:29

+0

不幸的是,共享轴消失了,必须手动删除标签。这是不幸的:(。什么,作品类型的工作是使用'subplot_kw = {'可调':'box-forced','aspect':'equal'}'作为'subplots'的选项。轴标签仍然显示为“共享”轴... – rubenvb 2015-11-05 10:33:54

+0

OK ...你在哪里找到'可调='box-forced'' API描述?我在这里变得有点疯狂... – Atcold 2017-02-08 15:05:24

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相同的属性。

我希望这有助于:)