python - 如何在条形图中标记部分
问题描述
标记所有部分的最简单方法是什么?
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”
解决方案
标记每个彩色部分的最简单方法是使用图例。使用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()
推荐阅读
- javascript - 读取服务器上的表单数据
- firebase - 无法从 createUserWithEmailAndPassword 的 firebase 响应访问 stsTokenManager
- java - 如何在JAVA中替换对象属性中的特殊字符
- shell - 实际有效的 CygWin 替代方案
- swift - 如何将具有关联类型的协议与 ObservableObject 一起使用?
- android - 即使状态发生变化,我的可组合视图也不会自行重组
- python - 为什么这个递归函数返回None?
- javascript - Promise 没有捕捉到异步函数抛出的错误
- c# - 在表 'Jobs' 上引入 FOREIGN KEY 约束 'FK_Jobs_AspNetUsers_UserId' 可能会导致循环或多个级联路径
- c# - C# UDP 多人运动不连贯(不是因为插值)