因此,我使用plt.subplots()在一个输出中绘制多个图,同时使用matplotlib魔术函数。
无论如何,我注意到我对每个“变量”(或列)对我的数据进行了相同的计算。基本上,它看起来像这样
%matplotlib inline
fig, (ax1,ax2,ax3) =plt.subplots(nrows=1, ncols=3, sharex=False, sharey=True, figsize=(5,5))
#PAPERLESS
ACCOUNT= df.groupby(['PAPERLESS'])['ACCOUNT'].count().rename('ACCOUNT')
cases=df.groupby(['PAPERLESS'])['cases'].sum().rename('cases')
paperless=pd.concat([ACCOUNT,cases],axis=1)
tempdf=paperless
tempdf['percent']=tempdf['cases']/tempdf['ACCOUNT']*100
print(tempdf)
graph1=tempdf['percent'].plot(y='percent',kind='bar', ax=ax1)
ax1.set_title("Paperless")
graph1.yaxis.set_major_formatter(mtick.PercentFormatter())
plt.tight_layout()因此,我显然是从“无纸化”变量开始,获取数据中每一列的计费计数。现在,我想计算每个变量的帐户,从我的案例数中找出它们的百分比,然后绘制它。如何使用函数或某种类型的for循环来实现这一点?我有大约15个变量,所以手动操作并不是很有效.
谢谢,我将更新我提出的问题,因为这个问题是公开的。
发布于 2018-04-06 19:25:40
我想这能帮你做到
import pandas as pd
%matplotlib inline
fig, axes =plt.subplots(nrows=1, ncols=3, sharex=False, sharey=True, figsize=(5,5))
aggregators = {'ACCOUNT':'count', 'cases': 'sum'}
variables = ['PAPERLESS', 'More PAPERLESS', 'PAPEERLESS NOT'] #For example
'''
# One way to get all the variables
variables = list(df.columns)
variables.remove('ACCOUNT')
variables.remove('cases')
'''
for variable, ax in zip(variables, axes):
mid = df.groupby(variable)['ACCOUNT', 'cases'].agg(aggregators) #Map a function to each column
percts = (mid.ACCOUNT / mid.cases) * 100 #Return a pd.Series with the percentages since you only plot that anyways
percts.plot(kind='bar', ax=ax) #Only plot percentage
ax.set_title(variable)https://stackoverflow.com/questions/49699247
复制相似问题