如何为 pandas 专栏的每一组创建一个子图 [英] How to create a subplot for each group of a pandas column

查看:37
本文介绍了如何为 pandas 专栏的每一组创建一个子图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在泰坦尼克数据集中,我需要创建一个图表,显示所有等级的乘客幸免于难的百分比。此外,它还应该有三个饼图。1级生存和死亡,2级生存和死亡,3级。

如何才能实现这一点?我已经尝试过这种类型的代码,但它生成了错误的值。

import pandas as pd
import seaborn as sns  # for dataset

df_titanic = sns.load_dataset('titanic')

   survived  pclass     sex   age  sibsp  parch     fare embarked  class    who  adult_male deck  embark_town alive  alone
0         0       3    male  22.0      1      0   7.2500        S  Third    man        True  NaN  Southampton    no  False
1         1       1  female  38.0      1      0  71.2833        C  First  woman       False    C    Cherbourg   yes  False
2         1       3  female  26.0      0      0   7.9250        S  Third  woman       False  NaN  Southampton   yes   True

c1s = len(df_titanic[(df_titanic.pclass==1) & (df_titanic.survived==1)].value_counts())
c2ns = len(df_titanic[(df_titanic.pclass==1) & (df_titanic.survived==0)].value_counts())

此代码生成的值为真,但我需要它出现在3个饼图中

df_titanic.groupby(['pclass' ,'survived']).size().plot(kind='pie', autopct='%.2f')

班级:1、2、3成活:0、1

推荐答案

  1. 使用 pandas 获取子图的正确方法是重塑数据框架。pandas.crosstab用于整形数据帧
  2. 然后使用pandas.DataFrame.plotkind='pie'subplots=True绘制。
  • 已添加用于格式化的额外代码
    • 旋转pclass标签
    • 情节标题
    • 自定义图例,而不是每个子图的图例
      • 指定图例的标签
      • 为标签数指定颜色
  • 测试于python 3.8.12pandas 1.3.4matplotlib 3.4.3
import seaborn as sns  # for titanic data only
import pandas as pd
from matplotlib.patches import Patch  # to create the colored squares for the legend

# load the dataframe
df = sns.load_dataset('titanic')

# reshaping the dataframe is the most important step
ct = pd.crosstab(df.survived, df.pclass)

# display(ct)
pclass      1   2    3
survived              
0          80  97  372
1         136  87  119

# plot and add labels
colors = ['tab:blue', 'tab:orange']  # specify the colors so they can be used in the legend
labels = ["not survived", "survived"]  # used for the legend
axes = ct.plot(kind='pie', autopct='%.1f%%', subplots=True, figsize=(12, 5),
               legend=False, labels=['', ''], colors=colors)

# flatten the array of axes
axes = axes.flat

# extract the figure object
fig = axes[0].get_figure()

# rotate the pclass label
for ax in axes:
    yl = ax.get_ylabel()
    ax.set_ylabel(yl, rotation=0, fontsize=12)
    
# create the legend
legend_elements = [Patch(fc=c, label=l) for c, l in zip(colors, labels)]
fig.legend(handles=legend_elements, loc=9, fontsize=12, ncol=2, borderaxespad=0, bbox_to_anchor=(0., 0.8, 1, .102), frameon=False)

fig.tight_layout()
fig.suptitle('pclass survival', fontsize=15)

格式化图形

未格式化的图形

axes = ct.plot(kind='pie', autopct='%.1f%%', subplots=True, figsize=(12, 5), labels=["not survived", "survived"])

这篇关于如何为 pandas 专栏的每一组创建一个子图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆