【问题标题】:How do I generate multiple plots from grouped data using Matplotlib or Seaborn?如何使用 Matplotlib 或 Seaborn 从分组数据中生成多个图?
【发布时间】:2019-10-14 22:05:31
【问题描述】:

我在 pandas 中有以下数据框:

它按数据集中参与者的年龄范围进行分组/索引。对于数据框中的每个年龄范围,我想生成一个条形图,其条形显示该特定年龄范围的离婚率、结婚率等。如何使用 matplotlib 或 seaborn 做到这一点?提前感谢您提供的任何帮助。

用于生成数据框的代码:

import numpy as np
import pandas as pd
import seaborn as sns
from matplotlib import pyplot as plt
plt.style.use('ggplot')

df = pd.DataFrame({
    'age_range': [(18, 28), (28, 38), (38, 48), (48, 58), (58, 68), (68, 78), (78, 88)],
    'divorced': [0.015837, 0.068826, 0.138132, 0.185022, 0.180258, 0.179211, 0.099502],
    'living with partner': [0.21040724, 0.14979757, 0.07392996, 0.06828194, 0.04506438, 0.01075269, 0.00995025],
    'married': [0.24208145, 0.51619433, 0.57198444, 0.54625551, 0.50429185, 0.37992832, 0.28855721],
    'never_married': [0.50904977, 0.23279352, 0.14202335, 0.08370044, 0.09012876,0.05734767, 0.05472637],
    'refused': [np.nan, np.nan, np.nan, np.nan, 0.00214592, np.nan, np.nan],
    'widowed': [np.nan, 0.00202429, 0.0155642 , 0.05506608, 0.12875536, 0.33691756, 0.53731343]
})

df.set_index('age_range', inplace=True)
df

【问题讨论】:

  • 很有可能。有很多方法可以做到这一点。您需要更具体地了解您想要什么样的条形图(例如,刻面、堆叠......)。您还应该以可复制的格式包含您的数据框
  • 您好,感谢您的反馈。我用可复制粘贴格式的数据框代码更新了帖子。我想要它的刻面。
  • 只需df.plot.bar()?

标签: python python-3.x pandas matplotlib seaborn


【解决方案1】:

由于这些百分比加起来往往等于 1,因此堆积条形图比较合适:

plt.style.use('ggplot')
ax = df.plot.bar(stacked=True)
ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))

结果:

【讨论】:

    【解决方案2】:

    如果您想要堆叠条形图并希望它带有色相,这对 seaborn 来说非常快:

    g = (
        df.stack()
          .to_frame('Count')
          .rename_axis(index=['Age Range', 'Status'])
          .reset_index()
          .pipe((sns.factorplot, 'data'), 
                x='Age Range', y='Count',
                hue='Status', kind='bar',
                size=3.5, aspect=1.86)
    
    )
    

    或者您可以按列分面:

    g = (
        df.stack()
          .to_frame('Count')
          .rename_axis(index=['Age Range', 'Status'])
          .reset_index()
          .pipe((sns.factorplot, 'data'), 
                x='Age Range', y='Count',
                col='Status', kind='bar',
                size=3.5, aspect=1.86, col_wrap=2)
    
    )
    

    【讨论】:

      猜你喜欢
      • 2020-02-21
      • 2023-01-20
      • 1970-01-01
      • 1970-01-01
      • 2021-10-14
      • 2019-10-21
      • 2023-03-16
      • 2018-08-23
      • 1970-01-01
      相关资源
      最近更新 更多