【问题标题】:what is major difference between histogram,countplot and distplot in Seaborn library?Seaborn 库中的直方图、计数图和分布图之间的主要区别是什么?
【发布时间】:2019-06-15 17:24:24
【问题描述】:

我认为它们看起来都一样,但肯定有一些不同。

它们都以单列作为输入,y 轴包含所有图的计数。

【问题讨论】:

    标签: python matplotlib visualization seaborn data-analysis


    【解决方案1】:

    那些绘图函数pyplot.histseaborn.countplotseaborn.displot 都是绘制单个变量频率的辅助工具。根据这个变量的性质,它们可能或多或少适合可视化。

    连续变量

    可以对连续变量x 进行直方图以显示频率分布。

    import matplotlib.pyplot as plt
    import numpy as np
    
    x = np.random.rand(100)*100
    hist, edges = np.histogram(x, bins=np.arange(0,101,10))
    plt.bar(edges[:-1], hist, align="edge", ec="k", width=np.diff(edges))
    
    plt.show()
    

    同样可以使用pyplot.histseaborn.distplot实现,

    plt.hist(x, bins=np.arange(0,101,10), ec="k")
    

    sns.distplot(x, bins=np.arange(0,101,10), kde=False, hist_kws=dict(ec="k"))
    

    distplot 包装 pyplot.hist,但除此之外还有一些其他功能,例如显示核密度估计。

    离散变量

    对于离散变量,直方图可能合适,也可能不合适。如果您使用 numpy.histogram,则 bin 需要正好位于预期的离散观测值之间。

    x1 = np.random.randint(1,11,100)
    
    hist, edges = np.histogram(x1, bins=np.arange(1,12)-0.5)
    plt.bar(edges[:-1], hist, align="edge", ec="k", width=np.diff(edges))
    plt.xticks(np.arange(1,11))
    

    也可以计算 x 中的唯一元素,

    u, counts = np.unique(x1, return_counts=True)
    plt.bar(u, counts, align="center", ec="k", width=1)
    plt.xticks(u)
    

    导致与上面相同的情节。主要区别在于并非所有可能的观察都被占用的情况。假设5 甚至不是您数据的一部分。直方图方法仍会显示它,但它不是唯一元素的一部分。

    x2 = np.random.choice([1,2,3,4,6,7,8,9,10], size=100)
    
    plt.subplot(1,2,1)
    plt.title("histogram")
    hist, edges = np.histogram(x2, bins=np.arange(1,12)-0.5)
    plt.bar(edges[:-1], hist, align="edge", ec="k", width=np.diff(edges))
    plt.xticks(np.arange(1,11))
    
    plt.subplot(1,2,2)
    plt.title("counts")
    u, counts = np.unique(x2, return_counts=True)
    plt.bar(u.astype(str), counts, align="center", ec="k", width=1)
    

    后者是seaborn.countplot 所做的。

    sns.countplot(x2, color="C0")
    

    因此适用于离散或分类变量。

    总结

    所有函数 pyplot.histseaborn.countplotseaborn.displot 都充当 matplotlib 条形图的包装器,如果认为手动绘制此类条形图过于繁琐,则可以使用。
    对于连续变量,可以使用pyplot.histseaborn.distplot。对于离散变量,seaborn.countplot 更方便。

    【讨论】:

    • 其实,我认为连续变量和离散变量,因此数值变量,应该用pyplot.histseaborn.displot表示,而seaborn.countplot应该用于分类变量。来自seaborn.countplot 的 seaborn 文档:“使用条形显示每个分类箱中的观察计数......计数图可以被认为是跨分类变量而不是定量变量的直方图”。见seaborn.pydata.org/generated/seaborn.countplot.html
    猜你喜欢
    • 2022-11-25
    • 1970-01-01
    • 2015-12-01
    • 2019-09-26
    • 2015-08-22
    • 2015-08-06
    • 2011-03-06
    • 2013-12-23
    • 2017-04-28
    相关资源
    最近更新 更多