首页 > 解决方案 > 通过分类字段创建连续字段的密度图

问题描述

我有下面的代码,它覆盖了直方图上的密度曲线。它为我的数据中的“新鲜”字段执行此操作,这是一个连续字段。我想创建通过“频道”字段中的唯一值过滤的类似图。例如,在 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.xpandasmatplotlibseaborn

解决方案


我认为 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});

使用 sns.FacetGrid 刻面的 KDE 直方图

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


推荐阅读