我有一個簡單的DataFrame。我無法理解或找到簡單的方法來標記每個條形圖。
import pandas as pd
import matplotlib.pyplot as plt.
印度 = pd. DataFrame({'Year' : [1980, 1984, 1988, 1992, 1996 , 2000 , 2004, 2008 , 2012。
2016 , 2020] 。,
'Gold' 。[1, 0,0,0, 0,0,1,0,1] 。
'Silver': [0,0,0,0。 0,1,0,2,1,2] 。
'Bronze' : [0,0,0,1。 1,0,2,4, 1,4] })
India = India.set_index('Year')
India.plot(kind='bar' , stacked = 'true' , figsize = (8,5)
plt.xticks(rotation = 0)
plt.legend(['金牌','銀牌','銅牌'] , title = "勛章類別" )
plt.title("奧林匹克獎牌趨勢--印度(1980 - 2020)")
plt.xlabel("舉辦的夏季奧運會(年)")
plt.ylabel("贏得的獎牌數量")
totals = India.sum(axis=1)
print(totalals)
y_offset = 4 Print(total)
我不知道該如何繼續下去。我只想把總數或 "y "的高度作為條形標簽。
我試過這里的解決方案,但總是得到每個單條的標簽,而不是整個條的標簽。
uj5u.com熱心網友回復:
一個簡單的解決方案是使用plt.text:
for x, y in enumerate(totals):
if y != 0:
plt.text(x, y, y, ha='center'/span>, va='bottom'/span>)
uj5u.com熱心網友回復:
IIUC你想在條形圖上標出總數。你就快到了,我看到你預先計算了總數并定義了一個偏移量。現在你需要捕獲Axes物件(ax = India.plot(...)),并在總數上回圈,以添加文本:
import pandas as pd
import matplotlib.pyplot as plt.
印度 = pd. DataFrame({'Year' : [1980, 1984, 1988, 1992, 1996 , 2000 , 2004, 2008 , 2012。
2016 , 2020] 。,
'Gold' 。[1, 0,0,0, 0,0,1,0,1] 。
'Silver': [0,0,0,0。 0,1,0,2,1,2] 。
'Bronze' : [0,0,0,1。 1,0,2,4, 1,4] })
India = India.set_index('Year')
ax = India.plot(kind='bar' , stacked = 'true' , figsize = (8,5)
plt.xticks(rotation = 0)
plt.legend(['金牌','銀牌','銅牌'] , title = "勛章類別" )
plt.title("奧林匹克獎牌趨勢--印度(1980 - 2020)")
plt.xlabel("舉辦的夏季奧運會(年)")
plt.ylabel("贏得的獎牌數量")
totals = India.sum(axis=1)
print(totalals)
y_offset = .
for x, t in enumerate(totals):
ax.text(x, t y_offset, t, ha='center')
輸出。

轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/312382.html
標籤:

