首页 > 解决方案 > Matplotlib 水平条形图向条形添加值

问题描述

使用以下代码:

mixedgenres.sort_values(by = "rating").plot(kind = "barh", color = "steelblue", legend = False, grid = True) 
for i, v in enumerate(mixedgenres.rating):
    plt.text(v + 1, i - 0.25, str(round(v, 2)), color='steelblue')

我得到以下图表: 在此处输入图像描述

如何在图形框架内包含值并左对齐,以便它们在一行中很好地放置在彼此下方?

以下是帮助弄清楚的示例数据:

sampledata = {'genre': ["Drama", "Western", "Horror", "Family", "Music", "Comedy", "Crime", "War"], 
              'rating': [7, 7.6, 8, 8.1, 7.8, 6.9, 7.5, 7.7]}
test = pd.DataFrame(sampledata, index = sampledata["genre"])
test

绘制样本数据

test.sort_values(by = "rating").plot(kind = "barh", color = "steelblue", legend = False, grid = True) 
for i, v in enumerate(test.rating):
    plt.text(v + 1, i - 0.25, str(round(v, 2)), color='steelblue')

结果

在此处输入图像描述

标签: pythonmatplotlib

解决方案


这是完整的工作解决方案(跳过导入)。两件事情:

  1. 您使用未排序的评级值进行标记和
  2. 您在水平方向上添加了太多的偏移量/偏移量。

编辑:@ImportanceOfBeingErnest 建议的文本垂直对齐

fig = plt.figure()
ax = fig.add_subplot(111)

sampledata = {'genre': ["Drama", "Western", "Horror", "Family", "Music", "Comedy", "Crime", "War"], 
              'rating': [7, 7.6, 8, 8.1, 7.8, 6.9, 7.5, 7.7]}
test = pd.DataFrame(sampledata,  index=sampledata['genre'])
test.sort_values(by = "rating").plot(kind = "barh", color = "steelblue", legend = False, grid = True, ax = ax) 
plt.xlim(0, 8.9)

for i, v in enumerate(sorted(test.rating)):
    plt.text(v+0.2, i, str(round(v, 2)), color='steelblue', va="center")

输出 在此处输入图像描述


推荐阅读