繁体   English   中英

如何注释条形图并添加自定义图例

[英]How to annotate a bar plot and add a custom legend

我正在尝试绘制一个如下图所示的条形图,我不确定如何在每一列顶部设置百分比值,并在右侧设置一个图例。 我的代码片段如下。 它正在工作,但是它缺少百分比值和图例

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM