seaborn分布图中的随机空白/条

2024-10-02 08:15:10 发布

您现在位置:Python中文网/ 问答频道 /正文

目标:我想从“苏黎世的狗”数据集(Kaggle)(使用Python)为2017年苏黎世注册狗的年龄制作一个分布函数。我正在使用的变量--“GEBURTSJAHR_HUND”-将每只注册的狗的出生年份作为int。 我已将其转换为“dog_age”变量(=2017-出生日期),并希望绘制分布函数。请参见下图,了解每个年龄组大小的排序列表

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

提前感谢,

亚瑟


Tags: of函数agepltax空白空格dog
1条回答
网友
1楼 · 发布于 2024-10-02 08:15:10

问题在于年龄列是离散的:它只包含很短范围的整数。默认情况下,直方图将值范围(浮点)划分为固定数量的存储单元,这些存储单元通常与那些整数不匹配。为了得到一个合适的直方图,需要显式地设置箱子,例如每一半有一个箱子

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

resulting plot

相关问题 更多 >

    热门问题