使用Matplotlib创建一个100%堆叠面积图。

8

我想知道如何在matplotlib中创建一个100%堆积面积图。在matplotlib页面上,我没有找到相关示例。

这里有人能向我展示如何实现吗?


3
这个示例怎么样? - user2423516
1
你尝试过什么吗?如果你有大部分可用的代码,通常在SO上会得到更好的回应。就目前而言,这个问题看起来像是“请替我完成我的工作”。@LogicalKnight指出的示例是一个很好的开始,可以让你完成95%的工作。 - tacaswell
1个回答

22

实现这一目标的简单方法是确保对于每个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)。
下面的代码是@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


非常感谢你的完善帮助!目前我正在使用 mpl 1.2.1 和 numpy 来绘制数据,但还没有时间再次查看这个问题。因此,我真的很高兴得到了这段好代码!谢谢,Thomas - Thomas Becker
我刚试了一下用这个方法来制作堆叠图,但每次尝试调用stackplot时都会抛出异常。Traceback (most recent call last): File "<pyshell#49>", line 1, in <module> ax.stackplot(pressures) AttributeError: 'AxesSubplot'对象没有'stackplot'属性 - Magic_Matt_Man
1
@Magic_Matt_Man,你使用的Python和Matplotlib版本是什么? - sodd
Python 2.7.3 和 MPL 1.1.1rc 运行在 Ubuntu Linux 64 位发行版上。 - Magic_Matt_Man
1
@Magic_Matt_Man 你应该将Matplotlib更新到更高版本,然后上面的代码就可以运行了。我不认为stackplot包含在1.1.1rc版本中。 - sodd
@nordev 没问题,现在我的模块正常工作了。基本示例可以很好地运行。现在我只需要弄清楚如何在我的应用程序中使用语法...感谢! - Magic_Matt_Man

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接