为划分为 bin 的数据绘制盒须图

draw a box and whisker plot for data divided into bins

我有一个包含两列(f1 和 f2)的数据框。您可以使用以下方法创建示例数据框:


# intialise data of lists. 
data = {'f1':[20,183,19,45,9173,11,482], 
        'f2':[771,8773,91,837,917,891,11]} 
  
# Create DataFrame 
d = pd.DataFrame(data) 
  
# Print the output. 
d 

我使用以下代码将数据帧分成 20 个 bin:

d['feature2'].value_counts(bins=20, sort=False)

但是,上面提到的代码行给出了每个箱子中的计数。我想将数据框分成 20 个箱子,然后为两个功能的每个箱子绘制盒须图。

我知道hexbin, hist2d有一个参数nbins:


fig, axes = plt.subplots(ncols=2, nrows=1, figsize=(21, 5))

nbins = 40
axes[0].set_title('Hexbin')
axes[0].hexbin(d.f1, d.f2, gridsize=nbins, cmap=plt.cm.BuGn_r)

# 2D Histogram
axes[1].set_title('2D Histogram')
axes[1].hist2d(d.f1, d.f2, bins=nbins, cmap=plt.cm.BuGn_r)

但箱线图不存在。因此,我想将我的数据框分成 20 个箱子,并且我想为每个箱子绘制两列的盒须图。我怎样才能做到这一点。将不胜感激。

编辑:

不太清楚到底需要什么。

这是一种使用 Seaborn 的方法。首先将数据框转换为“长”形式,然后为值创建 20 个 bin,最后为每个特征创建箱线图:

from matplotlib import pyplot as plt
import pandas as pd
import numpy as np
import seaborn as sns

d = pd.DataFrame({'f1': np.random.rand(100, 100).cumsum(axis=0).ravel(),
                  'f2': np.random.rand(100, 100).cumsum(axis=0).ravel()})
dlong = d.melt(var_name='feature', value_name='value')
dlong['bins'] = pd.cut(dlong['value'], 20)
fig, ax = plt.subplots(figsize=(20, 5))
sns.boxplot(data=dlong, x='bins', y='value', hue='feature', ax=ax)
ax.tick_params(axis='x', rotation=90)
plt.tight_layout()
plt.show()

这是使用相同的 bin 创建两个子图的方法:

d = pd.DataFrame({'f1': np.random.rand(100, 100).cumsum(axis=0).ravel(),
                  'f2': np.random.rand(100, 100).cumsum(axis=0).ravel()})
dlong = d.melt(var_name='feature', value_name='value')
dlong['bins'] = pd.cut(dlong['value'], 10)
fig, (ax1, ax2) = plt.subplots(nrows=2, figsize=(12, 10))
sns.boxplot(data=dlong[dlong['feature'] =='f1' ], x='bins', y='value', ax=ax1)
sns.boxplot(data=dlong[dlong['feature'] =='f2' ], x='bins', y='value', ax=ax2)
ax1.set_title('feature = f1')
ax2.set_title('feature = f2')