2017-08-02 19 views
0

使用plot.barh創建一個具有等間隔列的條形圖。 不過,我有,我想在情節使用不等距值(df1['dist'])列以提供額外的信息:如何創建不等間隔的條形圖?

df1 = pd.DataFrame(np.random.rand(5, 2), columns=['a', 'b']) 
df1['dist'] = pd.Series([1,5,6.5,15,45], index=df1.index) 

df1.plot.barh(['dist'],['a','b'],stacked=True, width=.6, color = ['y','b']) 
plt.show() 

這可能嗎?

+1

這是什麼庫使用 - 熊貓? – jcfollower

+0

@jcfollower是的,它是熊貓。 – mati

回答

2

您可以創建 '手工' 條形圖使用barh功能從matplotlib

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

df1 = pd.DataFrame(np.random.rand(5, 2), columns=['a', 'b']) 
df1['dist'] = pd.Series([1,5,6.5,15,45], index=df1.index) 

fig,ax = plt.subplots() 

ax.barh(df1['dist'],df1['a'],height =1) 
ax.barh(df1['dist'],df1['b'],left=df1['a'], height =1) 
plt.show() 

下面是結果:

enter image description here

我不知道如果這實際上看起來更好,因爲現在酒吧非常薄。但是,您可以使用參數height來調整它們。

+0

謝謝,它適用於一系列2個系列。但是,如果我增加更多系列,我會得到一些奇怪的結果 - 可能我誤解了這個概念?這裏是一個例子:'df1 = pd.DataFrame(np.random.rand(5,4),columns = ['a','b','c','d']) df1 ['dist'] = pd.Series([1,5,6.5,15,45],index = df1.index)ax.barh(df1 ['dist'],df1 ['a'],height = 1,color ='r' ) ax.barh(df1 ['dist'],df1 ['b'],left = df1 ['a'],height = 1,color ='g')ax.barh(df1 ['dist'] ,df1 ['c'],left = df1 ['b'],height = 1,color ='b') ax.barh(df1 ['dist'],df1 ['d'],left = df1 [ 'c'],height = 1,color ='k')' – mati

+0

爲我最近的評論找到了一個解決方案[here:](https://stackoverflow.com/a/16654564/4053508) – mati

+0

@mati你面對的問題用'left'關鍵字,它告訴'barh'在哪裏開始吧。對於第二列,「left」只是第一列的值,但對於第三列,則必須使用第一列和第二列的值的總和。如果你有三個以上的列,當然最好是在一個循環中完成這個操作,並將「左」值的運行總和存儲在一個專用列表中,就像在你鏈接的問題的答案之一中一樣。 –

相關問題