如何在barh()中使用xaxis_date()?

在下面的代码中,bdate和edate都是datetime.datetime()对象:

pylab.barh(ypos, edate - bdate, left=bdate, height=TRMWidth )

但这在dates.py.\u to \u ordinalf()中引发了一个属性错误:
文件“/library/frameworks/python.framework/versions/2.7/lib/python2.7/site packages/matplotlib/pyplot.py”,第1926行,位于barh
ret=ax.barh(底部、宽度、高度、左侧,**kwargs)
文件“/library/frameworks/python.framework/versions/2.7/lib/python2.7/site packages/matplotlib/axes.py”,第4774行,在barh中
方向='水平',**kwargs)
文件“/library/frameworks/python.framework/versions/2.7/lib/python2.7/site packages/matplotlib/axes.py”,第4624行,在bar中
width=self.convert_xUnits(宽度)
文件“/library/frameworks/python.framework/versions/2.7/lib/python2.7/site packages/matplotlib/artist.py”,第147行,位于Convert Xunits中
返回ax.xaxis.convert_单位(x)
文件“/library/frameworks/python.framework/versions/2.7/lib/python2.7/site packages/matplotlib/axis.py”,第1312行,采用转换单元
ret=self.converter.convert(x,self.units,self)
文件“/library/frameworks/python.framework/versions/2.7/lib/python2.7/site packages/matplotlib/dates.py”,第1125行,在convert中
返回日期2num(值)
文件“/library/frameworks/python.framework/versions/2.7/lib/python2.7/site packages/matplotlib/dates.py”,行260,日期2num
否则:返回np.asarray([_to_ordinalf(val)for val in d])
file“/library/frameworks/python.framework/versions/2.7/lib/python2.7/site packages/matplotlib/dates.py”,第189行,在“到”顺序中
基=浮点(dt.toordinal())
attributeError:“datetime.timedelta”对象没有“toordinal”属性
我想如果我能在Xaxis把约会时间推到一个新的地方去,那就太好了。
弄清楚细节;不算太多。有什么关于如何使约会可以和Xaxis联系的建议吗?


最佳答案:

发生的是Matplotlib实际上并没有使用日期时间对象进行绘图。
日期首先转换为内部浮点格式。转换没有设置为处理TimeDelta(可以说是一种疏忽)。
基本上你可以做你想要的,你只需要明确地将日期转换为matplotlib的内部格式,然后调用ax.xaxis_date()
作为一个快速的例子(其中大部分是生成要绘制的数据…):

import datetime as dt
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

def drange(start, end, interval=dt.timedelta(days=1)):
    output = []
    while start <= end:
        output.append(start)
        start += interval
    return output

# Generate a series of dates for plotting...
edate = drange(dt.datetime(2012, 2, 1), dt.datetime(2012, 6, 15), 
                      dt.timedelta(days=5))
bdate = drange(dt.datetime(2012, 1, 1), dt.datetime(2012, 5, 15), 
                      dt.timedelta(days=5))

# Now convert them to matplotlib's internal format...
edate, bdate = [mdates.date2num(item) for item in (edate, bdate)]

ypos = range(len(edate))
fig, ax = plt.subplots()

# Plot the data
ax.barh(ypos, edate - bdate, left=bdate, height=0.8, align='center')
ax.axis('tight')

# We need to tell matplotlib that these are dates...
ax.xaxis_date()

plt.show()