使用以下代码:
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')
结果
答案 0 :(得分:1)
这是完整的工作解决方案(跳过导入)。两件事:1)您正在使用 unsorted 评级值进行标记,以及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")