使用pandas.DataFrame.plot方法时的timeserie datetick问题

时间:2017-05-10 11:27:15

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

我在使用plot的{​​{1}}方法时发现了一些非常奇怪的东西。我正在使用pandas pandas.DataFrame。这是我的MWE:

0.19.1

当我尝试格式化我的xticklabels时,我得到了奇怪的beahviours,然后我找不到要理解的对象,我发现了以下内容:

  • 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() ,确认t[-1] - t[0] = Timedelta('7 days 00:00:00')是我的期望;
  • DateTimeIndexxt = [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,哎呀这是我的错误所在的位置)

Axis Ticks Numbering bug

看起来0481-01-03 00:00pandas整数转换之间存在一些不兼容性,但我无法找到解决此问题的方法。

如果我改为运行:

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

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

1 个答案:

答案 0 :(得分: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()

Like this?

相关问题