【问题标题】:Unnormalized histogram plots in Seaborn are not centered on X-axisSeaborn 中的非标准化直方图未以 X 轴为中心
【发布时间】:2020-08-21 21:54:25
【问题描述】:

我正在绘制一个值在两个不同数据集中出现的次数。一个图(图 1)完美地绘制了图表,条形图正好位于 x 轴上的数字上方。在第二个图(图 2)上,应该有两个条形图,一个在 1 x 轴值上方,另一个在 2 x 轴值上方,但两个条形图都很粗,并且在 x 轴上的 1 和 2 之间被压扁。如何让第二张图看起来像第一张图?

这是我在 Jupyter 笔记本中用来生成两个图的代码。

plot = sns.distplot(x7, kde=False)
for bar in plot.patches:
    h = bar.get_height()
    if h != 0:
        plot.text(bar.get_x() + bar.get_width() / 2,
                  h,
                  f'{h:.0f}\n',
                  ha='center',
                  va='center')

【问题讨论】:

    标签: python jupyter-notebook seaborn distribution kernel-density


    【解决方案1】:

    问题在于您使用的是用于连续分布的直方图,并将其用于离散数据。对于离散数据,最好创建明确的 bin。或者,可以将限制设置得更宽,以及在每个条形图上明确刻度。

    这是一个 0.2 宽的 bin 示例:

    import matplotlib.pyplot as plt
    import numpy as np
    import seaborn as sns
    
    data1 = np.random.choice(np.arange(1, 8), 200)
    data2 = np.random.choice(np.arange(1, 3), 40)
    
    fig, axs = plt.subplots(ncols=2)
    
    for data, ax in zip([data1, data2], axs):
        minx, maxx = data.min(), data.max()
        plot = sns.distplot(data, bins=np.arange(minx - 0.1, maxx+ 0.2, 0.2), kde=False, ax=ax)
        plot.set_xlim(minx-0.9, maxx+0.9)
        plot.set_xticks(np.unique(data))
        for bar in plot.patches:
            h = bar.get_height()
            if h != 0:
                plot.text(bar.get_x() + bar.get_width() / 2,
                          h,
                          f'{h:.0f}\n',
                          ha='center',
                          va='center')
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 2012-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-30
      相关资源
      最近更新 更多