2013-06-01 106 views
9

我想知道如何在matplotlib中創建100%堆積面積圖。在matplotlib頁面上我找不到它的例子。用matplotlib創建100%堆積面積圖

有人在這裏可以告訴我如何實現這一目標?

+3

這樣如何[示例](http://matplotlib.org/examples/pylab_examples/stackplot_demo.html)? – 2013-06-01 17:56:58

+1

你有試過什麼嗎?如果您主要使用代碼,您通常會在SO上獲得更好的響應。就目前而言,這個問題的內容是「請爲我做我的工作」。 @LogicalKnight指出的例子是一個好的開始,並讓你獲得95%的成功。 – tacaswell

回答

17

一個簡單的方法來實現這一目標是確保每一個x值,y值之和爲100

我假設你有一個數組舉辦的y值作爲例子下面,即

y = np.array([[17, 19, 5, 16, 22, 20, 9, 31, 39, 8], 
       [46, 18, 37, 27, 29, 6, 5, 23, 22, 5], 
       [15, 46, 33, 36, 11, 13, 39, 17, 49, 17]]) 

要確保列總計100個,您必須通過其列求和的y陣列劃分,然後乘以100這使得y值跨度從0到100,使得y軸的「單位」爲。如果改爲希望的y軸的值跨越的時間間隔從0到1,即使你不必在一個陣列如上組織的y值不通過100

乘,原則是一樣的;由y值組成的每個陣列中的對應元素(例如y1,y2等)應該總計爲100(或1)。

以下代碼是鏈接到他的評論中的example @LogicalKnight的修改版本。

import numpy as np 
from matplotlib import pyplot as plt 

fnx = lambda : np.random.randint(5, 50, 10) 
y = np.row_stack((fnx(), fnx(), fnx())) 
x = np.arange(10) 

# Make new array consisting of fractions of column-totals, 
# using .astype(float) to avoid integer division 
percent = y/y.sum(axis=0).astype(float) * 100 

fig = plt.figure() 
ax = fig.add_subplot(111) 

ax.stackplot(x, percent) 
ax.set_title('100 % stacked area chart') 
ax.set_ylabel('Percent (%)') 
ax.margins(0, 0) # Set margins to avoid "whitespace" 

plt.show() 

這給出如下所示的輸出。

enter image description here

+0

非常感謝您的幫助!我目前正在用mpl 1.2.1和numpy進行比較,以便首先繪製數據,並且沒有時間再次查看這個問題。因此,我很高興得到這段好的代碼! 乾杯托馬斯 –

+0

我試過這種製造STACK圖表自己剛纔和一個異常被拋出每次我打電話stackplot '回溯(最近最後一次通話)時間: 文件「」第1行 ax.stackplot(壓力) AttributeError:'AxesSubplot'對象沒有屬性'stackplot'' –

+1

@Magic_Matt_Man你使用的是什麼版本的Python和Matplotlib? – hooy