2010-02-09 26 views
40

我希望能夠用Python(最好使用matplotlib,但另一個庫也可以)生成堆棧線圖(類似於使用的方法here)。我怎樣才能做到這一點?如何使用matplotlib創建堆棧線圖?

這與他們的網站上的stacked bar graph example類似,但我希望酒吧的頂部與線段連接並且要填充下面的區域。我可以通過減少小節之間的差距和使用很多小節來估計這個值(但這看起來像是一個黑客,除此之外我不確定是否有可能)。

+5

該示例中的鏈路(http://www.whitehouse.gov/omb/budget/fy2003/images/bud20c.jpg)是破碎。你有更好的鏈接嗎? –

+0

使用來自pyplot包的stackplot()。 – AjayKumarBasuthkar

+0

這是一個老問題,但對於像我這樣在搜索中發現此問題的其他人,如果您使用的是熊貓數據框,則有一個新解決方案:'df = pd.DataFrame(np.random.rand(10,4 ),columns = ['a','b','c','d'])' 'df.plot.area();'來自http://pandas.pydata.org/pandas-docs/stable /visualization.html –

回答

46

我相信區地塊是這種類型的圖的常用詞,並記載於OP的具體實例,堆積面積地塊

Matplotlib沒有一個「亂用」的功能,結合的數據處理和繪圖/渲染步驟來創建這種類型的情節,但它很容易從提供的組件滾你自己由Matplotlib和NumPy完成。

下面第一堆疊數據的代碼,然後繪製劇情。

import numpy as NP 
from matplotlib import pyplot as PLT 

# just create some random data 
fnx = lambda : NP.random.randint(3, 10, 10) 
y = NP.row_stack((fnx(), fnx(), fnx())) 
# this call to 'cumsum' (cumulative sum), passing in your y data, 
# is necessary to avoid having to manually order the datasets 
x = NP.arange(10) 
y_stack = NP.cumsum(y, axis=0) # a 3x10 array 

fig = PLT.figure() 
ax1 = fig.add_subplot(111) 

ax1.fill_between(x, 0, y_stack[0,:], facecolor="#CC6666", alpha=.7) 
ax1.fill_between(x, y_stack[0,:], y_stack[1,:], facecolor="#1DACD6", alpha=.7) 
ax1.fill_between(x, y_stack[1,:], y_stack[2,:], facecolor="#6E5160") 

PLT.show() 

example of stacked area plot

+13

既然你想要非常完整,爲什麼不把它變成'stackplot(x,yn,colorlist)'並且向上遊提交一個功能請求錯誤? –

+0

如果你想爲這種圖形創建圖例,我認爲你需要使用代理「藝術家」http://matplotlib.sourceforge.net/users/legend_guide.html#using-proxy-artist –

+1

@honk其實,已經有一個[掛起的PR](https://github.com/matplotlib/matplotlib/pull/819)(應該很快合併)一個'stackplot'函數。 –

7

稍微不太冒昧的做法是首先使用折線圖並matplotlib.pyplot.fill_between。要模擬堆疊,您必須自己移動點。

x = np.arange(0,4) 
y1 = np.array([1,2,4,3]) 
y2 = np.array([5,2,1,3]) 
# y2 should go on top, so shift them up 
y2s = y1+y2 

plot(x,y1) 
plot(x,y2s) 
fill_between(x,y1,0,color='blue') 
fill_between(x,y1,y2s,color='red') 
+0

能否請您介紹一下fill_between()方法的參數?就好像我們正在填充x和y之間的某種顏色,但第三個變量是什麼? – khan

+0

@khan:http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes。fill_between –

48

matplotlib的較新版本包含的功能plt.stackplot,這使幾個不同的 「亂用」 的堆積面積圖:

import numpy as np 
import pylab as plt 

X = np.arange(0, 10, 1) 
Y = X + 5 * np.random.random((5, X.size)) 

baseline = ["zero", "sym", "wiggle", "weighted_wiggle"] 
for n, v in enumerate(baseline): 
    plt.subplot(2 ,2, n + 1) 
    plt.stackplot(X, *Y, baseline=v) 
    plt.title(v) 
    plt.axis('tight') 
plt.show() 

Stack Plot using plt.stackplot.

+0

'* Y'是什麼意思? –

2

如果你有一個數據幀,它是qui TE容易:

df = pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd']) 
df.plot.area(); 

enter image description here

來自:pandas documentation