如何使用python生成显示百分比而不是出现次数的图形?
我有1000名客户,他们的任期和合同状态各不相同(1表示他们已签订合同,0表示他们已解除合同),如下数据框所示:如何使用python生成显示百分比而不是出现次数的图形?,python,matplotlib,histogram,seaborn,percentage,Python,Matplotlib,Histogram,Seaborn,Percentage,我有1000名客户,他们的任期和合同状态各不相同(1表示他们已签订合同,0表示他们已解除合同),如下数据框所示: df=pd.DataFrame(列=['customer'、'liferature'、'contract\u status'] df['customer']=np.arange(1001) df['lexture']=np.random.randint(1200,df.shape[0]) df['合同状态][:200]=0 df['合同状态][200:]=1 我创建了一个柱状图,用
df=pd.DataFrame(列=['customer'、'liferature'、'contract\u status']
df['customer']=np.arange(1001)
df['lexture']=np.random.randint(1200,df.shape[0])
df['合同状态][:200]=0
df['合同状态][200:]=1
我创建了一个柱状图,用以下代码说明合同内和合同外客户的分布情况:
sns.set\u上下文('talk'))
sns.set_样式('darkgrid')
plt.rcParams[“figure.figsize”]=(10,8)
plt.hist(df[df['contract_status']==1]['liferature'],bin=50,alpha=0.5,label='contract')
plt.hist(df[df['contract_status']==0]['liferature'],bin=50,alpha=0.5,label='Non-contract')
plt.图例(位置='右上')
plt.xlabel(“任期”)
产品名称(“客户分布”)
plt.show()
以下是我尝试过的示例和预期的解决方案:
> exp = df[(df['tenure']>0) & (df['tenure']<10)]
> exp_plot = exp.groupby(['contract_status',
> 'tenure']).size().reset_index().pivot(columns='contract_status', index
> ='tenure', values=0)
> exp_plot['In contract'] = ((exp_plot[1]/(exp_plot[0] + exp_plot[1])) * 100).round(2)
> exp_plot['Out of contract'] = ((exp_plot[0]/(exp_plot[0] + exp_plot[1])) * 100).round(2)
> exp_plot.drop([0,1],axis=1,inplace=True)
> fig,ax = plt.subplots(figsize = (15,8))
> exp_plot.plot(kind='bar',stacked=True,ax =ax)
> ax.set(xlabel = 'tenure',ylabel='Percentage of customers',title= 'tenure' +
> by percentage',ylim=(0,100))
> ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))
>
> for p in ax.patches:
> width, height = p.get_width(), p.get_height()
> x, y = p.get_xy()
> ax.text(x+width/2, y+height/2, '{:.1f}%'.format(height),
> horizontalalignment='center',
> verticalalignment='center',size=14,color='white')
exp=df[(df[‘任期’]>0)和(df[‘任期’]exp\u plot=exp.groupby([‘合同状态’,
>“任期”]).size().reset_index().pivot(columns='contract_status',index
>='任期',值=0)
>exp_plot['在合同中]=(exp_plot[1]/(exp_plot[0]+exp_plot[1])*100。第二轮
>exp_plot['Out of contract']=(exp_plot[0]/(exp_plot[0]+exp_plot[1])*100。第二轮
>exp_plot.drop([0,1],轴=1,在位=True)
>图,ax=plt.子批次(图尺寸=(15,8))
>exp_plot.plot(kind='bar',stacked=True,ax=ax)
>ax.set(xlabel=‘任期’、ylabel=‘客户百分比’、title=‘任期’+
>按百分比’,ylim=(0100))
>ax.图例(loc='中间偏左',bbox_至_锚=(1,0.5))
>
>对于ax.patches中的p:
>宽度,高度=p.获取宽度(),p.获取高度()
>x,y=p.get_xy()
>ax.text(x+width/2,y+height/2,“{.1f}%.”格式(height),
>水平对齐='中心',
>垂直对齐=中心,尺寸=14,颜色=白色)
这个解决方案只适用于少数几个数据点——如上图所示,我仅将此示例用于0到10之间的任期。当我尝试将其应用于整个数据帧时,结果并不正确
我想创建一个类似于堆叠条形图的图形,以百分比而不是出现次数来显示分布,其中每个条形图将上升到1,阴影中的颜色将表示每个任期实例的合同内或合同外的客户数量。有一个密度
键如果设置为True
,它将生成一个标准化的直方图。如果不支持相同的功能,我会感到惊讶
应足以修改,例如:
plt.hist(df[df['contract_status'] == 1]['tenure'], bins = 50,alpha=0.5, label='Contract')
为此:
plt.hist(df[df['contract_status'] == 1]['tenure'], bins = 50, density=True, alpha=0.5, label='Contract')
(也许,你也应该考虑<代码> DF.PLUTE()/<代码>,如果它只是快速和肮脏的绘图).
如果我不清楚,很抱歉,但我想要一个类似于堆叠条形图的东西,每个任期都可以显示合同签订和终止的客户比例。我建议写一份详细的报告,更好地说明您现在得到了什么以及您希望得到什么。