gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 20:16:58 24 4
gpt4 key购买 nike

使用以下代码:

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

如何将值包含在图表框架内并向左对齐,以便将它们很好地放置在一行中?

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

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

结果

enter image description here

最佳答案

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

  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

关于python - Matplotlib 水平条形图向条形图添加值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52182746/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com