使用matplotlib创建100%堆积面积图 [英] Create a 100 % stacked area chart with matplotlib

查看:230
本文介绍了使用matplotlib创建100%堆积面积图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何在matplotlib中创建100%的堆积面积图.在matplotlib页面上,我找不到它的示例.

I was wondering how to create a 100 % stacked area chart in matplotlib. At the matplotlib page I couldn't find an example for it.

这里有人可以告诉我如何实现这一目标?

Somebody here can show me how to achieve that?

推荐答案

一种简单的方法是确保每个x值的y值总和为100.

A simple way to achieve this is to make sure that for every x-value, the y-values sum to 100.

我假设您将y值组织在一个数组中,如下例所示,即

I assume that you have the y-values organized in an array as in the example below, i.e.

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轴 percent .相反,如果您希望y轴的值跨越从0到1的间隔,请不要乘以100.

To make sure the column totals are 100, you have to divide the y array by its column sums, and then multiply by 100. This makes the y-values span from 0 to 100, making the "unit" of the y-axis percent. If you instead want the values of the y-axis to span the interval from 0 to 1, don't multiply by 100.

即使您没有像上面那样在 one 数组中组织y值,其原理也是相同的.每个数组中由y值组成的相应元素(例如y1y2等)的总和应为100(或1).

Even if you don't have the y-values organized in one array as above, the principle is the same; the corresponding elements in each array consisting of y-values (e.g. y1, y2 etc.) should sum to 100 (or 1).

下面的代码是示例 @LogicalKnight在其评论中链接的修改版本.

The below code is a modified version of the example @LogicalKnight linked to in his comment.

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()

这给出了如下所示的输出.

This gives the output shown below.

这篇关于使用matplotlib创建100%堆积面积图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆