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
:每组面积图所使用的的颜色,循环使用。颜色列表或元组。**kwargs
:Axes.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()