【问题标题】:Random empty spaces/bars in seaborn distribution plotseaborn 分布图中的随机空格/条
【发布时间】:2020-09-14 18:44:45
【问题描述】:

目标:我想根据“苏黎世的狗”数据集 (Kaggle)(使用 Python)为 2017 年在苏黎世注册的狗的年龄创建一个分布函数。我正在使用的变量 - 'GEBURTSJAHR_HUND' - 将每只注册狗的出生年份作为整数。 我已将其转换为“dog_age”变量(= 2017 -birth_date)并想绘制分布函数。请参阅下图,了解按年龄分组的排序列表。

Size of dog age groups

问题:我遇到的事实是我的分布函数的 x 轴中有空格/条。图表上显示了每个年龄,但在其中一些年龄之间是空条。 示例:1 和 2 是实条,但它们之间是空白。在 2 和 3 之间没有空白空间,但在 3 和 4 之间有。哪些值之间有空格似乎是随机的。

What my problematic distribution plot looks like at the moment

尝试过:我之前尝试了三件事来解决此问题。

  1. plt.xticks(...) 不幸的是,这只改变了 x 轴的美感。
  2. 尝试 ax = sns.distplot 后跟 ax.xaxis 股票行,但这没有达到预期的结果。
ax.xaxis.set_major_locator(ticker.MultipleLocator())
ax.xaxis.set_major_formatter(ticker.ScalarFormatter(0))
  1. 也许问题出在“dog_age”变量上? 使用了原始的birth_date 变量,但这也有同样的问题。

代码:

dfnew = pd.read_csv(dog17_filepath,index_col='HALTER_ID')
dfnew.dropna(subset = ["ALTER"], inplace=True)
dfnew['dog_age'] = 2017 - dfnew['GEBURTSJAHR_HUND']
b = dfnew['dog_age']

sns.set_style("darkgrid")
plt.figure(figsize=(15,5))
sns.distplot(a=b,hist=True)
plt.xticks(np.arange(min(b), max(b)+1, 1))
plt.xlabel('Age Dog', fontsize=12)
plt.title('Distribution of age of dogs', fontsize=20)

plt.show()

提前致谢,

亚瑟

【问题讨论】:

    标签: python matplotlib seaborn


    【解决方案1】:

    问题在于年龄列是离散的:它只包含一小部分整数。默认情况下,直方图将值范围(浮点数)划分为固定数量的箱,这些箱通常与这些整数不能很好地对齐。要获得合适的直方图,需要明确设置 bin,例如在每半个边界处绑定一个 bin。

    import matplotlib.pyplot as plt
    import numpy as np
    import pandas as pd
    import seaborn as sns
    
    dfnew = pd.read_csv('hundehalter.csv')
    dfnew.dropna(subset=["ALTER"], inplace=True)
    dfnew['dog_age'] = 2017 - dfnew['GEBURTSJAHR_HUND']
    b = dfnew['dog_age'][(dfnew['dog_age'] >= 0) & (dfnew['dog_age'] <= 25)]
    
    sns.set_style("darkgrid")
    plt.figure(figsize=(15, 5))
    sns.distplot(a=b, hist=True, bins=np.arange(min(b)-0.5, max(b)+1, 1))
    plt.xticks(np.arange(min(b), max(b) + 1, 1))
    plt.xlabel('Age Dog', fontsize=12)
    plt.title('Distribution of age of dogs', fontsize=20)
    plt.xlim(min(b), max(b) + 1)
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-06
      • 1970-01-01
      • 1970-01-01
      • 2018-03-03
      • 1970-01-01
      • 2020-04-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多