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

守給你的承諾、 提交于 2021-01-07 01:36:13

问题


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?

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


回答1:


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.

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



来源:https://stackoverflow.com/questions/61643619/unnormalized-histogram-plots-in-seaborn-are-not-centered-on-x-axis

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!