使用matplotlib在x轴上绘制datetimeindex会在pandas 0.15中创建错误的刻度,而0.14则相反

Dir*_*irk 12 python matplotlib pandas

我创建了一个简单的pandas数据帧,其中包含一些随机值和一个DatetimeIndex,如下所示:

import pandas as pd
from numpy.random import randint
import datetime as dt
import matplotlib.pyplot as plt

# create a random dataframe with datetimeindex
dateRange = pd.date_range('1/1/2011', '3/30/2011', freq='D')
randomInts = randint(1, 50, len(dateRange))
df = pd.DataFrame({'RandomValues' : randomInts}, index=dateRange)
Run Code Online (Sandbox Code Playgroud)

然后我用两种不同的方式绘制它:

# plot with pandas own matplotlib wrapper
df.plot()

# plot directly with matplotlib pyplot
plt.plot(df.index, df.RandomValues)

plt.show()
Run Code Online (Sandbox Code Playgroud)

(不要在同一个数字上同时使用这两个语句.)

我使用Python 3.4 64bitmatplotlib 1.4.使用pandas 0.14,两个语句都给我预期的图(他们使用略微不同的x轴格式,这是可以的;请注意,数据是随机的,因此图看起来不一样): 熊猫0.14:熊猫情节

pandas 0.14:matplotlib图

但是,当使用pandas 0.15时,pandas图看起来不错,但matplotlib图在x轴上有一些奇怪的刻度格式:

熊猫0.15:熊猫情节

pandas 0.15:matplotlib图

这种行为有什么好的理由以及为什么它从熊猫0.14变为0.15?

jor*_*ris 19

请注意,此错误已在pandas 0.15.1(https://github.com/pandas-dev/pandas/pull/8693)中修复,plt.plot(df.index, df.RandomValues)现在再次运行.


这种行为改变的原因是从0.15开始,pandas Index对象不再是一个numpy ndarray子类.但真正的原因是matplotlib不支持datetime64dtype.

作为一种解决方法,在您想要使用matplotlib plot函数的情况下,您可以使用以下命令将索引转换为python datetime to_pydatetime:

plt.plot(df.index.to_pydatetime(), df.RandomValues)
Run Code Online (Sandbox Code Playgroud)

更详细的说明:

因为Index不再是ndarray子类,所以matplotlib会将索引转换为带有dtype的numpy数组datetime64(之前,它保留了Index对象,其中标量作为Timestamp值返回datetime.datetime,是matplotlib可以处理的子类).在plot函数中,它调用np.atleast_1d()输入,该输入现在返回datetime64数组,matplotlib将其作为整数处理.

我打开了一个关于这个的问题(因为这可能有很多用途):https://github.com/pydata/pandas/issues/8614