Python条形图y轴显示百分比
我画了一个条形图。我希望yaxis以百分比显示值 我的代码:Python条形图y轴显示百分比,python,matplotlib,bar-chart,Python,Matplotlib,Bar Chart,我画了一个条形图。我希望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
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()
目前产出:
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()
# note the division here
ax.bar(df['name'],df['qty']/df['qty'].sum())
ax.yaxis.set_major_formatter(mtick.PercentFormatter())
输出:
如果您希望将
数量
值作为百分比,饼图不是更有意义吗?第二个图是我所期望的。@大陆乘以100
:-)@大陆刚刚意识到将xmax=1
传递到PercentFormatter
也可以不乘以100
。这太好了。让我试试。
fig, ax = plt.subplots()
# note the division here
ax.bar(df['name'],df['qty']/df['qty'].sum())
ax.yaxis.set_major_formatter(mtick.PercentFormatter())