【问题标题】:create density plots of continuous field by categorical field通过分类字段创建连续字段的密度图
【发布时间】:2019-06-04 21:54:31
【问题描述】:

我有下面的代码,它覆盖了直方图上的密度曲线。它为我的数据中的“新鲜”字段执行此操作,这是一个连续字段。我想通过“通道”字段中的唯一值过滤创建类似的图。例如,在 pandas 中创建类似于我想要完成的直方图,我会使用:

data_df.hist(column=‘Fresh’,by=‘Channel’)

谁能建议如何为下面的 seaborn 代码做类似的事情?

代码:

import seaborn as sns

sns.distplot(data_df[‘Fresh’], hist=True, kde=True, 
                             bins=int(data_df.shape[0]/5), color = 'darkblue', 
                             hist_kws={'edgecolor':'black'},
                             kde_kws={'linewidth': 4})

数据

  Channel  Fresh
0        2  12669
1        2   7057
2        2   6353
3        1  13265
4        2  22615
5        2   9413
6        2  12126
7        2   7579
8        1   5963
9        2   6006

【问题讨论】:

    标签: python-3.x pandas matplotlib seaborn


    【解决方案1】:

    我认为 Seaborn 的方法是创建一个 FacetGrid,然后在 map 上添加一个轴级绘图功能。在你的情况下:

    g = sns.FacetGrid(data_df, col='Channel', margin_titles=True)
    g.map(sns.distplot, 
          'Fresh',
          bins=int(data_df.shape[0]/5),
          color='darkblue', 
          hist_kws={'edgecolor': 'black'},
          kde_kws={'linewidth': 4});
    

    查看文档了解更多信息:https://seaborn.pydata.org/tutorial/axis_grids.html

    【讨论】:

      【解决方案2】:

      或者,您可以基于Channel groupby 您的DataFrame,然后将两组绘制在不同的子图中

      import pandas as pd
      import seaborn as sns
      import matplotlib.pyplot as plt
      
      data_df = pd.DataFrame({'Channel': [2, 2, 2, 1, 2, 2, 2, 2, 1, 2],
                              'Fresh': [12669,  7057,  6353, 13265, 22615,  
                                        9413, 12126,  7579,  5963,6006]})
      df1 = data_df.groupby('Channel')
      
      fig, axes = plt.subplots(nrows=1, ncols=len(df1), figsize=(10, 3))
      
      for ax, df in zip(axes.flatten(), df1.groups):
          sns.distplot(df1.get_group(df)['Fresh'], hist=True, kde=True, 
                                   bins=int(data_df.shape[0]/5), color = 'darkblue', 
                                   hist_kws={'edgecolor':'black'},
                                   kde_kws={'linewidth': 4}, ax=ax)
      
      plt.tight_layout()    
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-01-12
        • 1970-01-01
        • 1970-01-01
        • 2015-09-18
        • 1970-01-01
        • 2023-01-28
        相关资源
        最近更新 更多