Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/360.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/xamarin/3.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 按色调组调整seaborn countplot_Python_Pandas_Matplotlib_Statistics_Seaborn - Fatal编程技术网

Python 按色调组调整seaborn countplot

Python 按色调组调整seaborn countplot,python,pandas,matplotlib,statistics,seaborn,Python,Pandas,Matplotlib,Statistics,Seaborn,我有一个类似这样的数据集 地位 年龄组 失败 18-25 失败 26-30 失败 18-25 成功 41-50 显示比例的最简单方法是通过sns.histogram(…,multiple='fill')。要强制对年龄组和状态进行排序,创建有序类别会有所帮助 下面是一些使用seaborn 0.11.1测试的示例代码: 导入matplotlib.pyplot作为plt 从matplotlib.ticker导入百分比格式化程序 导入seaborn作为sns 将numpy作为np导入 作为pd进口熊猫

我有一个类似这样的数据集

地位 年龄组 失败 18-25 失败 26-30 失败 18-25 成功 41-50
显示比例的最简单方法是通过
sns.histogram(…,multiple='fill')
。要强制对年龄组和状态进行排序,创建有序类别会有所帮助

下面是一些使用seaborn 0.11.1测试的示例代码:

导入matplotlib.pyplot作为plt
从matplotlib.ticker导入百分比格式化程序
导入seaborn作为sns
将numpy作为np导入
作为pd进口熊猫
data=pd.DataFrame({'status':np.random.choice(['Success','Failure'],100,p=[.7,.3]),
“年龄组”:np.随机选择(['18-45','45-60','>60'],100,p=[.2,3,5]))
数据['age_group']=pd.Category(数据['age_group'],有序=True,类别=['18-45','45-60','>60'])
数据['status']=pd.Categorical(数据['status'],有序=True,类别=['Failure','Success'])
ax=sns.histplot(y='age\u group',hue='status',multiple='fill',data=data)
ax.xaxis.set\u major\u格式化程序(百分比格式化程序(1))
ax.set_xlabel('百分比')
plt.show()

现在,为了创建问题的精确图,一些熊猫人工可能会创建以下数据框:

  • 计算每个年龄组和状态的值
  • 除以每个年龄组的总数
也许可以采取一些快捷方式,但这就是我如何尝试与pandas打交道的方式(编辑自@PatrickFitzGerald的评论:使用
pd.crosstab()
):

#df=data.groupby(['status',age\u group']).agg(len).重置索引(level=0)\
#.pivot(columns='status').droplevel(level=0,axis=1)
#总计=df.总和(轴=1)
#df['Success']/=总计
#df['Failure']/=总计
df=pd.交叉表(数据['age_group'],数据['status'],normalize='index')
df1=df.melt(var\u name='status',value\u name='percentage',ignore\u index=False).reset\u index()
ax=sns.barplot(y='status',x='percentage',hue='age\u group',palete='rocket',data=df1)
ax.xaxis.set\u major\u格式化程序(百分比格式化程序(1))
ax.set_xlabel('百分比')
ax.set_ylabel(“”)
plt.show()

快捷方式:
df=pd.crosstab(数据['age\u group',数据['status',normalize='index')
ax.xaxis.set\u major\u格式化程序('{x:.0%}')
@PatrickFitzGerald非常感谢!