
如何獲得每個條形右側的計數和百分比???目前我只知道如何獲得計數。
import pandas as pd
import matplotlib.pyplot as plt
age = ['0-17','18-60','61-80']
df3 = pd.DataFrame(data={'Male':[82,550,25], 'Female':[72,309,7]}, index=age)
print(df3)
ax = df3.plot(kind='barh', ylabel='Age', title='Passenger Count by Age and Sex')
ax.set(xlabel='No. of Passengers')
for c in ax.containers:
# set the bar label
ax.bar_label(c, fmt='%.0f', label_type='edge')
ax.legend(title='Sex', bbox_to_anchor=(1, 1.02), loc='upper left')
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
plt.show()
uj5u.com熱心網友回復:
該函式
- 如果條形值為 0,以下選項將添加一個條件,以具有空字串。
- 賦值運算式 (
:=) 可用于python 3.8
- 賦值運算式 (
ax = df3.plot(kind='barh', ylabel='Age', title='Passenger Count by Age and Sex', width=0.75)
ax.set(xlabel='No. of Passengers')
tot = df.sum().sum()
# add annotations
for c in ax.containers:
# custom label calculates percent and add an empty string so 0 value bars don't have a number
labels = [f'{w/tot*100:0.1f}%\n{w}' if (w := v.get_width()) > 0 else '' for v in c]
ax.bar_label(c, labels=labels, label_type='edge', padding=0.3)
ax.margins(x=0.15)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/371890.html
標籤:Python 熊猫 matplotlib 注释 条形图
上一篇:調整等值線圖的繪制值
