簡體   English   中英

Python 條形圖 plot y軸顯示百分比

[英]Python Bar plot y axis display percentage

我已經繪制了一個條形 plot。 我想要 yaxis 以百分比顯示值。

我的代碼:

import matplotlib.ticker as mtick

df = 
     name    qty
0    Aple    200
1    Bana    67
2    Oran    10
3    Mang    8

ax=plt.bar(df['name'],df['qty'])
ax.yaxis.set_major_formatter(mtick.PercentFormatter())
plt.show()

目前output:

ax.yaxis.set_major_formatter(mtick.PercentFormatter())

AttributeError: 'BarContainer' object has no attribute 'yaxis'

plt.bar不返回軸實例。 我想你的意思是:

ax = df.plot.bar(x='name',y='qty')
ax.yaxis.set_major_formatter(mtick.PercentFormatter())

或者

fig, ax = plt.subplots()

ax.bar(df['name'],df['qty'])
ax.yaxis.set_major_formatter(mtick.PercentFormatter())

Output:

在此處輸入圖像描述

但是,從您嘗試 plot百分比猜測,我認為您想要:

fig, ax = plt.subplots()

# note the division here
ax.bar(df['name'],df['qty']/df['qty'].sum())
ax.yaxis.set_major_formatter(mtick.PercentFormatter())

Output:

在此處輸入圖像描述

暫無
暫無

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

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