2016-11-22 15 views
2

我使用包含錯誤欄(圍繞欄頂對稱)的熊貓barplot繪製數據,並且我想修改此圖中單個錯誤欄的範圍,以便它只顯示一半。我怎樣才能做到這一點?在pandas barplot中修改一個錯誤欄範圍

這裏有一個具體的例子:

import numpy as np 
import matplotlib.pyplot as plt 
import pandas as pd 

bars = pd.DataFrame(np.random.randn(2,2), index=['a','b'], columns=['c','d']) 
errs = pd.DataFrame(np.random.randn(2,2), index=['a','b'], columns=['c','d']) 

ax = bars.plot.barh(color=['r','g'],xerr=errs) 

它產生這樣一個情節:

barplot example with errorbars

我想事後訪問和修改的errorbar程度索引a和列d,以便它只顯示它的前半部分,即段[bar_top-err, bar_top]而不是[bar_top-err, bar_top+err] 。我試圖檢索以下matplotlib對象:

plt.getp(ax.get_children()[1],'paths')[0] 

,如果我沒有記錯,是一個Bbox,並介紹合適的對象,但我不能去修改它在我的陰謀。任何想法如何做到這一點?

+0

'型(plt.getp(斧頭。 get_children()[1],'paths')[0])'告訴我它實際上是一個'matplotlib.path.Path'。 – whrrgarbl

+0

當然,它實際上是'matplotlib.transforms.Bbox'類型的'plt.getp(ax.get_children()[1],'paths')[0] .get_extents()'。但具體而言,這並不能幫助我找出解決方案...... – fseyrl

回答

1

你幾乎在那裏,只需要修改和更新path.vertices中的座標。我冒昧地認爲你想要的誤差線面臨「去零」,而不是僅僅顯示它的負部分組成:

import numpy as np 
import matplotlib.pyplot as plt 
import pandas as pd 

bars = pd.DataFrame(np.random.randn(2,2), index=['a','b'], columns=['c','d']) 
errs = pd.DataFrame(np.random.randn(2,2), index=['a','b'], columns=['c','d']) 

ax = bars.plot.barh(color=['r','g'], xerr=errs) 
child = ax.get_children()[1] 

path = plt.getp(child, 'paths')[0] 
bar_top = path.vertices.mean(axis=0)[0] 

# replace the right tail if bar is negative or left tail if it's positive 
method = np.argmin if np.sign(bar_top)==1 else np.argmax 
idx = method(path.vertices, axis=0)[0] 
path.vertices[idx, 0] = bar_top 

plt.savefig('figs/hack-linecollections.png', dpi=150) 
plt.show() 

hack-linecollections

+0

太好了,謝謝!這完全解決了我的問題。 – fseyrl