Matplotlib水平条形图向条形图添加值

2024-03-29 08:33:50 发布

您现在位置:Python中文网/ 问答频道 /正文

代码如下:

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')

我得到以下图表: enter image description here

如何将值包含在图框内并向左对齐,以便将它们整齐地放在一行中彼此下面?在

以下是示例数据,可帮助您了解:

^{pr2}$

绘制样本数据

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')

结果呢

enter image description here


Tags: falsetrueforbyplotsortgridcolor
1条回答
网友
1楼 · 发布于 2024-03-29 08:33:50

这里是完整的工作解决方案(跳过导入)。有两件事: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")

输出enter image description here

相关问题 更多 >