首页 > 解决方案 > 如何在条形图中标记部分

问题描述

标记所有部分的最简单方法是什么?

x = ['A', 'B', 'C', 'D']
y1 = np.array([2, 4, 5, 1])
y2 = np.array([1, 0, 2, 3])
y3 = np.array([4, 1, 1, 1])

plt.bar(x, y1, color='#d67ed0')
plt.bar(x, y2, color='#e6ad12', bottom=y1)
plt.bar(x, y3, color='#13c5ed', bottom=y1+y2)

plt.show()

像“A”-Violet 在情节上标记为“2”

标签: pythonmatplotlibdata-visualizationbar-chart

解决方案


标记每个彩色部分的最简单方法是使用图例。使用plt.bar函数中的label参数为栏中的每种颜色分配一个类别。然后使用代码末尾的plt.legend()函数来显示图例。

import numpy as np
import pandas as pd
from matplotlib import pyplot as plt

x = ['A', 'B', 'C', 'D']
y1 = np.array([2, 4, 5, 1])
y2 = np.array([1, 0, 2, 3])
y3 = np.array([4, 1, 1, 1])

# increase figure size
plt.figure(figsize = (10,7))

# add labels to each color
plt.bar(x, y1, color='#d67ed0', label = 'Cars')
plt.bar(x, y2, color='#e6ad12', bottom=y1, label = 'Buses')
plt.bar(x, y3, color='#13c5ed', bottom=y1+y2, label = 'Trains')
plt.legend(loc = 1, fontsize = 18)

plt.show()

在此处输入图像描述


推荐阅读