【问题标题】:Timeserie datetick problems when using pandas.DataFrame.plot method使用 pandas.DataFrame.plot 方法时的 Timeserie datetick 问题
【发布时间】:2017-05-10 11:27:14
【问题描述】:

我刚刚在使用pandas.DataFrameplot 方法时发现了一些非常奇怪的东西。我正在使用熊猫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的like index比较多,跟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,哎呀这是我的错误所在)。

pandasmatplotlib 整数到日期转换之间似乎有些不兼容,但我不知道如何解决此问题。

如果我改为运行:

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 正确格式化我的刻度并避免这个问题?

更新

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

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

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

【问题讨论】:

  • 你试过stackoverflow.com/questions/12945971/…中的解决方案了吗?
  • 另见:stackoverflow.com/questions/24620712/… 由于不清楚使用 matplotlib 命令时您会遗漏什么(“很酷的东西等”完全不精确),所以在这里很难为您提供帮助。
  • @ImportanceOfBeingErnest,我想继续调用 DataFrame.plot,至少因为它处理图例的标签。
  • 这是XY Problem吗?
  • pandas 使用的日期表示与 matplotlib 完全不同。因此,您不能对 pandas 生成的日期使用 matplotlib 格式化程序。问题是,您想坚持这个(Y)还是想告诉我们实际的问题(XY 问题中的 X)。

标签: python-3.x pandas matplotlib plot datetime-format


【解决方案1】:

这就是你想要的吗?请注意,我缩短了 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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-21
    • 1970-01-01
    • 1970-01-01
    • 2020-05-12
    • 2019-09-28
    • 2015-01-02
    • 2011-12-28
    相关资源
    最近更新 更多