matplotlib之pyplot模块——堆积面积图、主题河流图(stackplot)

概述

stackplot函数作用是绘制堆积面积图、主题河流图、流图(streamgraph)。

stackplot函数的签名为:matplotlib.pyplot.stackplot(x, *args, labels=(), colors=None, baseline='zero', data=None, **kwargs)

参数说明如下:

  • x:形状为(N,)的类数组结构,即尺寸为N的一维数组。必备参数。
  • y:形状为(M,N)的类数组结构,即尺寸为(M,N)的二维数组。必备参数。y参数有两种应用方式。
    • stackplot(x, y)y的形状为(M, N)
    • stackplot(x, y1, y2, y3)y1, y2, y3, y4 均为一维数组且长度为N
  • baseline:基线。字符串,取值范围为{'zero', 'sym', 'wiggle', 'weighted_wiggle'}。默认值为'zero'。可选参数。
  • 'zero':以0为基线,比如绘制简单的堆积面积图。
  • 'sym':以0上下对称,有时被称为主题河流图。
  • 'wiggle':所有序列的斜率平方和最小。
  • 'weighted_wiggle': 类似于'wiggle',但是增加各层的大小作为权重。绘制出的图形也被称为流图(streamgraph)。
  • labels:为每个数据系列指定标签。长度为N的字符串列表。
  • colors:每组面积图所使用的的颜色,循环使用。颜色列表或元组。
  • **kwargsAxes.fill_between支持的关键字参数。

stackplot函数的返回值为PolyCollection对象。

案例:演示baseline属性

在这里插入图片描述

import numpy as np
import matplotlib.pyplot as plt

labels = ['G1', 'G2', 'G3', 'G4', 'G5']
first = [20, 34, 30, 35, 27]
second = [25, 32, 34, 20, 25]
third = [21, 31, 37, 21, 28]
fourth = [26, 31, 35, 27, 21]
data = [first, second, third, fourth]

x = range(len(labels))
data = np.array(data)
baseline = ['zero', 'sym', 'wiggle', 'weighted_wiggle']
fig, axes = plt.subplots(1, 4, figsize=(13, 3))
for ax, b in zip(axes, baseline):
    ax.stackplot(x, data, labels=labels, baseline=b)
    ax.set_xlim(0, 4)
    ax.set_xticks(x)
    ax.set_title(b)
    ax.legend()
plt.show()

案例:演示y属性

在这里插入图片描述

import numpy as np
import matplotlib.pyplot as plt

# data from United Nations World Population Prospects (Revision 2019)
# https://population.un.org/wpp/, license: CC BY 3.0 IGO
year = [1950, 1960, 1970, 1980, 1990, 2000, 2010, 2018]
population_by_continent = {
    'africa': [228, 284, 365, 477, 631, 814, 1044, 1275],
    'americas': [340, 425, 519, 619, 727, 840, 943, 1006],
    'asia': [1394, 1686, 2120, 2625, 3202, 3714, 4169, 4560],
    'europe': [220, 253, 276, 295, 310, 303, 294, 293],
    'oceania': [12, 15, 19, 22, 26, 31, 36, 39],
}

fig, ax = plt.subplots()
ax.stackplot(year, population_by_continent.values(),
             labels=population_by_continent.keys())
ax.legend(loc='upper left')
ax.set_title('World population')
ax.set_xlabel('Year')
ax.set_ylabel('Number of people (millions)')

plt.show()
  • 4
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值