摘要介绍可视化过程中常见的两种堆叠图的使用场景和matplotlib实现方式。 一.堆叠柱状图(Stacked Bar Chart)1.1定义堆叠柱状图可以形象地展示一个大分类包含的每个小分类的数据,以及各个小分类的占比,显示的是单个项目与整体之间的关系。堆叠柱状图分为两种类型:
1.2使用场景适用场景:
不适用场景:
1.3实现在matplotlib中使用 import numpy as np
import matplotlib.pyplot as plt
# 使用的数据集
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],
}
# 初始化figure和axes
fig, ax = plt.subplots()
sum = np.zeros((1, len(year))).reshape(-1)
# 绘图
for i in population_by_continent:
ax.bar(year, population_by_continent.get(i), label=i, alpha=0.8, bottom=sum, width=5)
sum += population_by_continent.get(i)
# 添加图例和标题
ax.legend(loc='upper left')
ax.set_title('World population')
ax.set_xlabel('Year')
ax.set_ylabel('Number of people (millions)')
plt.show()
实现效果如下: 柱状堆叠图.png
二.堆叠面积图(Stacked Area Chart)2.1定义堆叠区域图将多个数据集绘制为垂直堆叠的区域。堆叠面积图和基本面积图一样,唯一的区别就是图上每一个数据集的起点不同,起点是基于前一个数据集的,用于显示每个数值所占大小随时间或类别变化的趋势线,展示的是部分与整体的关系。 堆叠面积图上的最大的面积代表了所有的数据量的总和,是一个整体。各个叠起来的面积表示各个数据量的大小,这些堆叠起来的面积图在表现大数据的总量分量的变化情况时格外有用。 在堆叠面积图的基础之上,将各个面积的因变量的数据使用加和后的总量进行归一化就形成了百分比堆叠面积图。该图并不能反映总量的变化,但是可以清晰的 2.2使用场景适用场景:
不适用场景:
2.3实现使用 作用:绘制堆叠面积图
参数1:x:数组,指定横轴。 参数2:*args,y:数组,指定要绘制的数据。 参数3:labels:字符串列表:指定每个绘制数据的标签。 参数4:colors:颜色列表:指定堆叠区域的着色,不必与y完相同,颜色会循环使用。 参数5:baseline:限定字符串:指定计算基线的方法,可选:
参数6:data:未知 参数7:**kwargs:接收的关键字参数传递给 import numpy as np
import matplotlib.pyplot as plt
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(), alpha=0.8)
ax.legend(loc='upper left')
ax.set_title('World population')
ax.set_xlabel('Year')
ax.set_ylabel('Number of people (millions)')
plt.show()
实现效果如下: 堆叠面积图.png
|
|