Seaborn中未归一化的直方图不在X轴上居中

问题描述 投票:0回答:1

我正在绘制一个值在两个不同的数据集中出现的次数。一个图(图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')

plot1plot2

python jupyter-notebook seaborn distribution kernel-density
1个回答
0
投票

问题是,您正在使用直方图表示连续分布,并将其用于离散数据。对于离散数据,最好创建显式容器。

这里是一个宽度为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):
    plot = sns.distplot(data, bins=np.arange(data.min() - 0.1, data.max() + 0.2, 0.2), kde=False, ax=ax)
    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()
© www.soinside.com 2019 - 2024. All rights reserved.