简体   繁体   English

Python 条形图 plot y轴显示百分比

[英]Python Bar plot y axis display percentage

I have plotted a bar plot.我已经绘制了一个条形 plot。 I want the yaxis display values in percentage.我想要 yaxis 以百分比显示值。

My code:我的代码:

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

Present output:目前output:

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

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

plt.bar does not return the axis instance. plt.bar不返回轴实例。 I think you mean:我想你的意思是:

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

Or或者

fig, ax = plt.subplots()

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

Output: Output:

在此处输入图像描述

However, guessing from you trying to plot percentage , I think you want:但是,从您尝试 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: Output:

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM