2016-08-05 79 views
2

我想顯示一個條形圖pandas 0.18.1其中不同列的值顯示在彼此的頂部而不是添加。所以這是我認爲沒有「疊加」堆疊條形圖,它增加了所有堆棧值。因此,在下面熊貓「堆疊」條形圖的值不添加到給出的高度

import pandas 
from pandas import DataFrame 

so_example = DataFrame([(15 , 0 , 0 , 4),(16, 0, 1, 4),(17 , 0 , 0 , 6)]).set_index(0) 
so_example.plot.bar(stacked=True) 

的例子

這給Dataframe

>>> so_example 
    1 2 3 
0   
15 0 0 4 
16 0 1 4 
17 0 0 6 

我拿到第二點 「16」 的1 + 4 = 5一個最大高度。相反,我希望最大高度爲4,綠色顯示的「1」就像現在一樣。

stacked bar plot

如何做到這一點沒有人爲減去。對不起,我不知道這些「堆積」的情節被稱爲所以我所有的搜索未能產生一個簡單的解決方案。

回答

2

請檢查下面的代碼,這不是一個全面的解決方案,但基本達到你想要的。

import pandas as pd 
import matplotlib.pyplot as plt 

so_example = pd.DataFrame([(15 , 0 , 0 , 4),(16, 0, 1, 4),(17 , 0 , 0 , 6)]).set_index(0) 
fig = plt.figure() 
ax = fig.add_subplot(111) 
_max = so_example.values.max()+1 
ax.set_ylim(0, _max) 
so_example.ix[:,1].plot(kind='bar', alpha=0.8, ax=ax, color='r') 
ax2 = ax.twinx() 
ax2.set_ylim(0, _max) 
so_example.ix[:,2].plot(kind='bar', alpha=0.8, ax=ax2, color='b') 
ax3 = ax.twinx() 
ax3.set_ylim(0, _max) 
so_example.ix[:,3].plot(kind='bar', alpha=0.8, ax=ax3, color='g') 

fig.savefig('c:\haha.png') 
fig.show() 

enter image description here


這裏是我的想法:

  1. 首先,我想爲你做同樣的事情,試圖找到一些plug and play的解決方案,但似乎沒有
  2. 然後我試着玩的價值觀,但你明確地說你不要想要人爲地玩這些價值觀。我個人認爲這取決於你如何定義artifical,我的意思是在繪製它之前做一些Dataframe的數據處理並不困難。
  3. 無論如何,這裏我們跳到第三個解決方案,這是與axis玩。由於基本上,您的要求是使條形圖疊加方式但重疊。我的意思是通常stacked bar意味着你在彼此之間堆疊互不重疊,這就是爲什麼它被稱爲stack。但既然你想組織的方式酒吧的最小值是在很前面,第二小值處於第2,等等等等...

所以在這裏,我用twinx()爲每個數據集創建不同的軸層,爲了讓我更容易一些,我沒有對它們排序,只是使用alpha=0.8來更改透明度。而且我沒有使用函數來完成整個事情。無論如何,我認爲這是一種方法。