Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/281.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python条形图y轴显示百分比_Python_Matplotlib_Bar Chart - Fatal编程技术网

Python条形图y轴显示百分比

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

我画了一个条形图。我希望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()
目前产出:

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