【问题标题】:x axis gets transformed to floatsx 轴转换为浮点数
【发布时间】:2018-02-09 22:57:49
【问题描述】:

我试图绘制按年份分组的数据,并且对于每一年,我都想计算用户数量。下面,我只是将日期列从浮点数转换为整数。

这是我的情节

如果你看到 x 轴,我的年份代码似乎变成了一个浮点数,每个代码相距 0.5 个刻度。

我怎样才能把它变成一个纯粹的整数?


更改 groupby 具有相同的结果:


将年份列转换为字符串格式后,刻度仍然相隔 2 个空格

df['year'] = df['year'].astype(str)

【问题讨论】:

  • 您似乎是按系列分组的。试试df_train.groupby('year').count()['id'].plot()
  • 是的,结果相同
  • 试试df['year'] = df['year'].astype(int)df['year'] = df['year'].astype(str)
  • 它已经在 'int' dtype 中。但是当我改为'str'时它起作用了。太奇怪了。感谢您的帮助!
  • 其实这个勾还是很奇怪,你可以看到更新

标签: python pandas matplotlib


【解决方案1】:

期望使用整数数据将导致 matplotlib 轴仅显示整数是不合理的。最后,每个轴都是一个数字浮点轴。

刻度和标签由定位器和格式化程序确定。而且 matplotlib 不知道您只想绘制整数。

一些可能的解决方案:

告诉默认定位器使用整数

默认定位器是AutoLocator,它接受属性integer。所以你可以把这个属性设置为True:

ax.locator_params(integer=True)

例子:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

data = pd.DataFrame({"year" : [2010,2011,2012,2013,2014],
                     "count" :[1000,2200,3890,5600,8000] })

ax = data.plot(x="year",y="count")
ax.locator_params(integer=True)

plt.show()

使用固定定位器

您可以使用ax.set_ticks() 仅勾选数据框中存在的年份。

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

data = pd.DataFrame({"year" : [2010,2011,2012,2013,2014],
                     "count" :[1000,2200,3890,5600,8000] })

data.plot(x="year",y="count")
plt.gca().set_xticks(data["year"].unique())
plt.show()

将年份转换为日期

您可以将年份列转换为日期。对于日期,自动进行更好的刻度标记。

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

data = pd.DataFrame({"year" : [2010,2011,2012,2013,2014],
                     "count" :[1000,2200,3890,5600,8000] })

data["year"] = pd.to_datetime(data["year"].astype(str), format="%Y")
ax = data.plot(x="year",y="count")

plt.show()

在所有情况下,您都会得到这样的结果:

【讨论】:

  • 使用 pd.to_datetime,为什么 df['year'] = df['date_account_created'].dt.year 不起作用。
  • 因为.dt.year 给你一个整数,所以这个答案的第一段再次适用。
【解决方案2】:
import matplotlib.pyplot as plt

# Use min and max to get the range of years to use in axis ticks
year_min = df['year'].min()
year_max = df['year'].max()

df['year'] = df['year'].astype(str) # Prevents conversion to float

plt.xticks(range(year_min, year_max, 1)) # Sets plot ticks to years within range

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-28
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-06
    • 1970-01-01
    相关资源
    最近更新 更多