使用 pandas.DataFrame.plot 方法时出现 Timeserie datetick 问题

2024-04-02

我刚刚在使用时发现了一些非常奇怪的事情plot的方法pandas.DataFrame。我正在使用熊猫0.19.1。这是我的 MWE:

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

t = pd.date_range('1990-01-01', '1990-01-08', freq='1H')
x = pd.DataFrame(np.random.rand(len(t)), index=t)

fig, axe = plt.subplots()
x.plot(ax=axe)
plt.show(axe)

xt = axe.get_xticks()

当我尝试格式化 xticklabels 时,我得到了奇怪的行为,然后我检查了对象以进行理解,并发现了以下内容:

  • t[-1] - t[0] = Timedelta('7 days 00:00:00'),确认DateTimeIndex是我所期望的;
  • xt = [175320, 175488], xticks是整数,但它们不等于自纪元以来的天数(我不知道它是什么);
  • xt[-1] - xt[0] = 168还有更多类似的索引,数量相同len(x) = 169.

这解释了为什么我无法使用以下命令成功格式化我的斧头:

axe.xaxis.set_major_locator(mdates.HourLocator(byhour=(0,6,12,18)))
axe.xaxis.set_major_formatter(mdates.DateFormatter("%a %H:%M"))

第一个引发错误,表示生成的蜱太多 我的第一个刻度的第二个显示是Fri 00:00但应该是Mon 00:00(实际上matplotlib假设第一个刻度是0481-01-03 00:00,哎呀,这就是我的错误所在)。

看起来有些不兼容pandas and matplotlib整数到日期的转换但我不知道如何解决这个问题。

如果我改为运行:

fig, axe = plt.subplots()
axe.plot(x)
axe.xaxis.set_major_formatter(mdates.DateFormatter("%a %H:%M"))
plt.show(axe)

xt = axe.get_xticks()

一切都按预期进行,但我想念所有很酷的功能pandas.DataFrame.plot方法如曲线标记等。这里xt = [726468. 726475.].

如何使用正确格式化我的报价pandas.DataFrame.plot方法而不是axe.plot并避免这个问题?

Update

问题似乎与日期表示的基础数字的起源和比例(单位)有关。无论如何,我无法控制它,即使强制它为正确的类型:

t = pd.date_range('1990-01-01', '1990-01-08', freq='1H', origin='unix', units='D')

matplotlib 和 pandas 表示之间存在差异。而且我找不到这个问题的任何文档。


这就是你想要的吗?请注意,我缩短了 date_range 以便更容易查看标签。

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

t = pd.date_range('1990-01-01', '1990-01-04', freq='1H')
x = pd.DataFrame(np.random.rand(len(t)), index=t)

# resample the df to get the index at 6-hour intervals
l = x.resample('6H').first().index

# set the ticks when you plot. this appears to position them, but not set the label
ax = x.plot(xticks=l)

# set the display value of the tick labels
ax.set_xticklabels(l.strftime("%a %H:%M"))
# hide the labels from the initial pandas plot
ax.set_xticklabels([], minor=True)
# make pretty
ax.get_figure().autofmt_xdate()

plt.show()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 pandas.DataFrame.plot 方法时出现 Timeserie datetick 问题 的相关文章

随机推荐