温馨提示×

Matplotlib怎么创建具有层次结构的条形图

小亿
82
2024-05-21 11:43:32
栏目: 编程语言

在Matplotlib中,创建具有层次结构的条形图可以通过使用多个bar函数来实现。您可以通过不同的颜色或不同的高度来区分不同层次的条形图。

以下是一个创建具有层次结构的条形图的示例代码:

import matplotlib.pyplot as plt

# 数据
data = {
    'A': {'2019': 10, '2020': 15, '2021': 20},
    'B': {'2019': 5, '2020': 10, '2021': 15},
    'C': {'2019': 8, '2020': 12, '2021': 18}
}

years = ['2019', '2020', '2021']
colors = ['red', 'blue', 'green']

# 创建图表
fig, ax = plt.subplots()

# 遍历每个数据点,并创建条形图
for i, (label, values) in enumerate(data.items()):
    bottom = None
    for j, year in enumerate(years):
        height = values[year]
        if bottom is not None:
            ax.bar(label, height, bottom=bottom, color=colors[j])
        else:
            ax.bar(label, height, color=colors[j])
        if bottom is None:
            bottom = height
        else:
            bottom += height

# 设置图例和标签
ax.legend(years)
ax.set_ylabel('Value')
ax.set_title('Hierarchical Bar Chart')

plt.show()

在这个示例中,我们首先定义了数据,其中包含三个类别(A、B和C)和三个年份(2019、2020和2021)的值。然后,我们遍历每个类别的数据,并使用bar函数创建具有不同颜色和高度的条形图。最后,我们添加图例和标签,然后显示图表。

您可以根据自己的数据和需求修改代码来创建具有不同层次结构的条形图。

0