[英]Create a 100 % stacked area chart with matplotlib
我想知道如何在matplotlib中創建100%堆積面積圖。 在matplotlib頁面上,我找不到它的示例。
這里有人可以告訴我如何實現這一目標?
一種簡單的方法是確保每個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的間隔,請不要乘以100。
即使您沒有將y值組織在上面的一個數組中,原理也是一樣的。 每個數組中由y值組成的相應元素(例如y1
, y2
等)的總和應為100(或1)。
下面的代碼是@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()
這給出了如下所示的輸出。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.