Python 使用matplotlib在x轴上绘制datetimeindex会在0.15和0.14之间创建错误的刻度

Python 使用matplotlib在x轴上绘制datetimeindex会在0.15和0.14之间创建错误的刻度,python,matplotlib,pandas,Python,Matplotlib,Pandas,我用一些随机值和DatetimeIndex创建了一个简单的pandas数据框,如下所示: 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',

我用一些随机值和DatetimeIndex创建了一个简单的pandas数据框,如下所示:

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)
然后我用两种不同的方式绘制它:

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

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

plt.show()
(请勿在同一图形上同时使用这两个语句。)

我使用Python 3.4 64位和matplotlib 1.4。对于pandas 0.14,这两个语句都给出了预期的绘图(它们使用的x轴格式略有不同,这是可以的;请注意,数据是随机的,因此绘图看起来不一样):

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


这种行为有什么好的原因吗?为什么它从pandas 0.14变为0.15?

注意,这个错误在pandas 0.15.1()中被修复了,
plt.plot(df.index,df.RandomValues)
现在又能正常工作了


行为发生这种变化的原因是,从0.15开始,pandas
Index
对象不再是numpy ndarray子类。但真正的原因是matplotlib不支持
datetime64
dtype

作为一种解决方法,如果您想使用matplotlib
plot
函数,您可以使用
将索引转换为python datetime,以_pydatetime

plt.plot(df.index.to_pydatetime(), df.RandomValues)

更详细的解释:

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


我对此提出了一个问题(因为这可能会有很多用处):

使用matplotlib 1.5.0,这“很有效”:

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)

fig, ax = plt.subplots()
ax.plot('RandomValues', data=df)

一个解决方法是调用
到_pydatetime
plt.plot(df.index.to _pydatetime(),df.RandomValues)
。您可能是指
到_pydatetime()
(答案中没有“s”,输入相同的错误),然后它工作得很好。啊,是的,确实,谢谢!在我的回答中编辑了它谢谢你为这篇文章开篇所做的努力!解决方法很好,允许我使用pandas 0.15而不必做太多更改:)matplotlib 2.1.0和pandas 0.21.0也面临同样的问题。使用
to_pydatetime
的变通方法仍然有效。是的,这将在即将发布的0.21.1版本中修复(请参阅)