Seaborn 中的非标准化直方图不以 X 轴为中心

Unnormalized histogram plots in Seaborn are not centered on X-axis

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

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

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')

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

这是一个 bin 宽度为 0.2 的示例:

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()