pandas 绘图-x轴转换为浮点数 [英] pandas plotting - x axis gets transformed to floats
问题描述
我正在尝试按年份分组我的数据,并且每年我要统计用户数.在下面,我只是将日期列从float转换为integer.
I am trying to plot my data grouped by year, and for each year, i want to count the number of users. Below, i just transformed the date column from float to integer.
这是我的情节
如果您看到x轴,则我的年度股票代号似乎已经变成浮动货币,并且每个股票代号相距0.5个代号.
If you see the x-axis, my year ticker seems to have become a float and the each ticker is 0.5 tick apart.
我如何使它纯粹是整数?
How do i make this purely an integer?
更改groupby具有相同的结果:
Changing the groupby has the same result:
将年列转换为字符串格式后,滴答号仍相隔2个空格
ticks are still 2 spaces apart after converting the year column to a string format
df['year'] = df['year'].astype(str)
:
推荐答案
使用整数数据将导致matplotlib轴仅显示整数的期望是不合理的.最后,每个轴都是数字浮点轴.
The expectation that using integer data will lead a matplotlib axis to only show integers is not justified. At the end, each axis is a numeric float axis.
刻度和标签由定位器和格式化程序确定.而且matplotlib不知道您只想绘制整数.
The ticks and labels are determined by locators and formatters. And matplotlib does not know that you want to plot only integers.
一些可能的解决方案:
默认定位器是AutoLocator
,它接受属性integer
.因此,您可以将此属性设置为True
:
The default locator is a AutoLocator
, which accepts an attribute integer
. So you may set this attribute to 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()
,您可以仅勾选数据框中显示的年份.
Using a fixed locator
You may just tick only the years present in the dataframe by using 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()
将年份转换为日期
您可以将Year列转换为日期.对于日期,自动进行更好的刻度标记.
Convert year to date
You may convert the year column to a date. For dates much nicer ticklabeling takes place automatically.
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()
在所有情况下,您都会得到以下信息:
In all cases you would get something like this:
这篇关于 pandas 绘图-x轴转换为浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!