2013-06-01 161 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