一种简单的方法是确保每个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 npfrom matplotlib import pyplot as pltfnx = 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 divisionpercent = y / y.sum(axis=0).astype(float) * 100fig = 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()这给出了如下所示的输出。



