关于python:直方图在Seaborn中的bin大小

Histogram bin size in seaborn

我正在使用Seaborn的FacetGrid绘制一些直方图,并且我认为自动bin大小调整仅使用每个类别的数据(而不是每个子图),这会导致一些奇怪的结果(请参见y = 2中的瘦绿色垃圾桶):

1
2
g = sns.FacetGrid(df, row='y', hue='category', size=3, aspect=2, sharex='none')
_ = g.map(plt.hist, 'x', alpha=0.6)

Seaborn histogram

是否有一种方法(使用Seaborn,而不是回落到matplotlib)使每个图的直方图bin大小相等?

我知道我可以手动指定所有bin宽度,但这会迫使所有直方图都在相同的x范围内(请参阅笔记本)。

笔记本:https://gist.github.com/alexlouden/42b5983f5106ec92c092f8a2697847e6


您需要为plt.hist定义一个包装器功能,该功能本身会进行色相分组,例如

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
%matplotlib inline

import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

tips = sns.load_dataset("tips")
tips.loc[tips.time =="Lunch","total_bill"] *= 2

def multihist(x, hue, n_bins=10, color=None, **kws):
    bins = np.linspace(x.min(), x.max(), n_bins)
    for _, x_i in x.groupby(hue):
        plt.hist(x_i, bins, **kws)

g = sns.FacetGrid(tips, row="time", sharex=False)
g.map(multihist,"total_bill","smoker", alpha=.5, edgecolor="w")

enter image description here