簡體   English   中英

Matplotlib 中條形圖中條形圖上方的值

[英]Values above the bars in a barchart in Matplotlib

我有以下代碼用於 matplotlib 中的條形圖

import matplotlib.pyplot as plt; plt.rcdefaults()
import numpy as np
import matplotlib.pyplot as plt

objects = ('2004', '2005', '2006', '2007', '2008', '2009', '2010', '2011', '2012', '2013', '2014', '2015', '2016', '2017', '2018')
y_pos = np.arange(len(objects))
performance = [8.5,9.1,9.7, 10.6, 11.4, 12.6, 13.2, 13.4, 14.7, 15.4, 16.2, 16.7, 17.0, 17.5, 18.0]

fig, ax = plt.subplots(figsize=(18,5))



plt.bar(y_pos, performance, align='center', alpha=0.5, color="green")
plt.xticks(y_pos, objects)
plt.ylim(0, 20)
plt.ylabel('Share in %',  fontsize = 16)
plt.xlim(-0.6, len(objects) - 0.4)
ax.tick_params(axis='both', which='major', labelsize=14)
plt.savefig('Share_Of_Renewables_Europe.png', edgecolor='black', dpi=400, bbox_inches='tight',
           figsize=(18,5) )

for i, performance in enumerate(performance):
    ax.text(performance - 0, i + .25, str(performance), color='black', fontweight='bold')

plt.show()

我希望有高於條形的值。 我使用了來自How to display the value of the bar on each bar with pyplot.barh()? 但它看起來不正確。 在這里您可以看到輸出: 在此處輸入圖片說明

任何人都可以幫助我嗎?

您在ax.text使用了錯誤的變量ax.text 使用以下內容。 另外,不要兩次使用performance變量。 我現在用perf

for i, perf in enumerate(performance):
    ax.text(i, perf + .25, str(perf), color='black', 
            ha='center', fontweight='bold')

在此處輸入圖片說明

i是 x 位置的索引, performance是條形(y 位置)的高度。 plt.text的前兩個參數是plt.text的 x 和 y 位置。

for i, performance in enumerate(performance):
    ax.text(i, performance + .25, str(performance), color='black', fontweight='bold')

在 ax.text 調用中,替換:

performance - 0

和:

i - 0.15

嘗試這個:

xlocs = ax.get_xticks()

for i, performance in enumerate(performance):
    ax.text(xlocs[i] - .25, performance + .25, str(performance), color='black', fontweight='bold')

暫無
暫無

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

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