2010-07-08 76 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相同的屬性。

我希望這有助於:)