【问题标题】:Histogram bin size in seabornseaborn 中的直方图 bin 大小
【发布时间】:2017-07-05 00:45:20
【问题描述】:

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

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

有没有办法(使用 Seaborn,而不是退回到 matplotlib)使每个图的直方图 bin 大小相等?

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

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

【问题讨论】:

    标签: python matplotlib histogram seaborn


    【解决方案1】:

    您需要为 plt.hist 定义一个包装函数,该函数自己进行色调分组,类似于

    %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")
    

    【讨论】:

    • 感谢您的回答!我一直在玩这个,看起来multihist 在每个直方图的每个色调中调用一次 - 因此在函数内手动设置 bin 实际上最终与plt.hist 自动执行相同的结果。我更新了我的笔记本:gist.github.com/alexlouden/42b5983f5106ec92c092f8a2697847e6
    • 你没有正确改编我给你的例子。如果你看,你会发现FacetGrid 没有hue,而是由multihist 函数处理。
    • 哦,对不起,我的错误。谢谢,这将工作!我希望有一种方法可以在 Seaborn 中更优雅地做到这一点