python - 使用 matplotlib 创建 100% 堆积面积图

标签 python matplotlib stacked-area-chart

我想知道如何在 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 值组成的数组中的相应元素(例如 y1y2 等)总和应为 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

关于python - 使用 matplotlib 创建 100% 堆积面积图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16875546/

相关文章:

python - 如何避免循环导入

Python依赖分析器库

java - 如何使用 Prefuse 制作堆积面积图?

python - matplotlib colorbar 不工作(由于垃圾收集?)

python - Python Matplotlib stackplot 中的标签区域

JavaFX - StackedAreaChart 和方法 setLowerBound

python - Tensorflow:保存评估指标

python - 当SQL语句不返回任何行时,停止Python引发错误

python - 如何在 Python 中用空圆圈绘制散点图?

matplotlib pyplot imshow 图像之间的紧密间距