首页 > 解决方案 > 如何使用for循环将每个轴绘制在另一个轴之上

问题描述

我正在尝试从 Titanic 数据集中获取可视化:

import seaborn as sns

fig, axs = plt.subplots(nrows=5, ncols=1)
X=['sex', 'cabin', 'port_of_embarkation', 'is_boy', 'is_married_female']

for ax, x in zip(axs, X):
    sns.barplot(x, y='survived', data=main_df, estimator=lambda x: sum(x==1)*100.0/len(x))

where X是分类列的向量,main_df并且survived是二元列。

我们的想法是让这五个图彼此重叠,但是当前输出如下所示:

在此处输入图像描述

我在结构中缺少什么?有没有其他图书馆可以完成这项任务?

数据

   passengerid  survived      socio_economic_status  \
0            1       0.0  lower_socioeconomic_class   
1            2       1.0  upper_socioeconomic_class   
2            3       1.0  lower_socioeconomic_class   
3            4       1.0  upper_socioeconomic_class   
4            5       0.0  lower_socioeconomic_class   

                                                name     sex   age  \
0                            Braund, Mr. Owen Harris    male  22.0   
1  Cumings, Mrs. John Bradley (Florence Briggs Th...  female  38.0   
2                             Heikkinen, Miss. Laina  female  26.0   
3       Futrelle, Mrs. Jacques Heath (Lily May Peel)  female  35.0   
4                           Allen, Mr. William Henry    male  35.0   

   lateral_family_members  vertical_family_members            ticket     fare  \
0                       1                        0         A/5 21171   7.2500   
1                       1                        0          PC 17599  71.2833   
2                       0                        0  STON/O2. 3101282   7.9250   
3                       1                        0            113803  53.1000   
4                       0                        0            373450   8.0500   

  cabin port_of_embarkation  total_number_of_purchased_cabins  \
0   NaN                   S                               NaN   
1     C                   C                               1.0   
2   NaN                   S                               NaN   
3     C                   S                               1.0   
4   NaN                   S                               NaN   

  is_married_female   is_boy  
0       not_married  not_boy  
1           married  not_boy  
2       not_married  not_boy  
3           married  not_boy  
4       not_married  not_boy  

标签: pythonfor-loopseaborn

解决方案


您忘记为每个图指定轴,因此它将它们全部绘制在同一轴上。

for ax, x in zip(axs, X):
    sns.barplot(ax=ax, x=x, y='survived', data=main_df, estimator=lambda x: sum(x==1)*100.0/len(x))

推荐阅读