python - 如何注释条形图并添加自定义图例
问题描述
我正在尝试绘制一个如下图所示的条形图,我不确定如何在每列顶部设置百分比值,并在右侧设置图例。我的代码片段如下。它正在工作,但是它缺少百分比值和图例。
import matplotlib.pyplot as plt; plt.rcdefaults()
import numpy as np
import matplotlib.pyplot as plt
objects = ('18-25', '26-30', '31-40', '40-50')
y_pos = np.arange(len(objects))
performance = [13, 18, 16, 3]
width = 0.35 # the width of the bars
plt.bar(y_pos, performance, align='center', alpha=0.5, color=('red', 'green', 'blue', 'yellow'))
plt.xticks(y_pos, objects)
plt.ylabel('%User', fontsize=16)
plt.title('Age of Respondents', fontsize=20)
width = 0.35
plt.show()
解决方案
- 图例颜色与绘图颜色略有不同,因为
alpha=0.5
, 已被删除。 - imagecolorpicker.com用于选择校正蓝色和绿色。
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Patch
color = ('red', '#00b050', '#00b0f0', 'yellow')
objects = ('18-25', '26-30', '31-40', '40-50')
y_pos = np.arange(len(objects))
performance = [13, 18, 16, 3]
width = 0.35 # the width of the bars
plt.bar(y_pos, performance, align='center', color=color)
plt.xticks(y_pos, objects)
plt.ylim(0, 20) # this adds a little space at the top of the plot, to compensate for the annotation
plt.ylabel('%User', fontsize=16)
plt.title('Age of Respondents', fontsize=20)
# map names to colors
cmap = dict(zip(performance, color))
# create the rectangles for the legend
patches = [Patch(color=v, label=k) for k, v in cmap.items()]
# add the legend
plt.legend(title='Number of Trips', labels=objects, handles=patches, bbox_to_anchor=(1.04, 0.5), loc='center left', borderaxespad=0, fontsize=15, frameon=False)
# add the annotations
for y, x in zip(performance, y_pos):
plt.annotate(f'{y}%\n', xy=(x, y), ha='center', va='center')
注释资源 - 来自matplotlib v3.4.2
推荐阅读
- php - laravel 7:如何在原始/查询构建器中使用 if/case 语句显示数据
- python - 如何从 Entry 小部件中获取文本?
- r - 在 R 中使用 Keras 拟合模型时出现数据错误
- mingw - 为什么在msys中构建时openblas认为我正在使用Cygwin
- r - 警告:服务器错误:找不到函数“renderDT”
- node.js - 猫鼬模式异步方法不等待
- r - R中打印语句的评估顺序
- python - scipy.optimize.minimize 对初始猜测没有改善
- node.js - 如何通过 Restful 对 Mongoose 请求进行用户验证
- python - 实现 Karatsuba 算法时的整数除法