pandas plotting - x轴转换为浮点数

时间:2018-02-09 22:57:50

标签: python pandas matplotlib

我正在尝试绘制按年份分组的数据,并且每年都要计算用户数量。下面,我刚刚将日期列从float转换为整数。

这是我的情节enter image description here

如果你看到x轴,我的年份股票代码似乎变成了一个浮动,每个股票代码相差0.5。

我如何使这纯粹是一个整数?

更改groupby具有相同的结果: enter image description here

将year列转换为字符串格式

后,

tick仍然相隔2个空格

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

enter image description here

2 个答案:

答案 0 :(得分:2)

期望使用整数数据将导致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()

在所有情况下,你都会得到这样的东西:

enter image description here

答案 1 :(得分:0)

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

希望这有帮助!