Seaborn中未归一化的直方图图未以X轴为中心 [英] Unnormalized histogram plots in Seaborn are not centered on X-axis

查看:69
本文介绍了Seaborn中未归一化的直方图图未以X轴为中心的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am graphing the number of occurrences that a value occurs in two different datasets. One plot (plot 1) graphs perfectly, the bars are right above the numbers on the x-axis. On the second plot (plot 2), there should be two bars, one above the 1 x-axis value and the other above the 2 x-axis value, but both bars are thick and squashed between 1 and 2on the x-axis. How do I get the second graph to look like the first graph?

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

This is the code that I used in Jupyter notebook to generate both plots.

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

推荐答案

问题是您正在使用用于连续分布的直方图,并将其用于离散数据.对于离散数据,最好创建显式容器. (可选)可以将限制设置得更宽,也可以在每个小节处设置明确的刻度.

The problem is that you are using a histogram meant for a continuous distribution and use it for discrete data. With discrete data it is best to create explicit bins. Optionally, the limits can be set wider, as well as explicit ticks at each of the bars.

这里是一个0.2宽的垃圾箱的示例:

Here is an example with bins that are 0.2 wide:

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

这篇关于Seaborn中未归一化的直方图图未以X轴为中心的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆