簡體   English   中英

Matplotlib水平條形圖將值添加到條形

[英]Matplotlib horizontal bar plot add values to bars

使用以下代碼:

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

結果

在此處輸入圖片說明

這是完整的工作解決方案(跳過導入)。 有兩件事: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")

產量 在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM