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

rik*_*ikb 7 python datetime matplotlib bar-chart

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

pylab.barh(ypos, edate - bdate, left=bdate, height=TRMWidth )
Run Code Online (Sandbox Code Playgroud)

但这会在dates.py._to_ordinalf()中抛出AttributeError方式:

文件"/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行,条形宽度= self.convert_xunits(width)文件"/ Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/artist.py",第147行,在convert_xunits中返回ax.xaxis.convert_units(x)文件"/ Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/axis.py",第1312行,在convert_units中ret = self.converter.convert(x,self.units,self)文件"/ Library /Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/dates.py",第1125行,在转换中返回date2num(value)在date2num文件中输入文件"/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/dates.py",第260行:return np.asarray([_ to_ordinalf(val)for val in d])文件"/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/dates.py",第189行,在_to_ordinalf base = float(dt.toordinal( ))

AttributeError:'datetime.timedelta'对象没有属性'toordinal'

我认为如果我能在xaxis上推出日期时间并让它解决细节问题会很棒; 没那么多.有关如何使日期与xaxis相关的任何建议?

Joe*_*ton 14

发生的事情是matplotlib实际上并没有使用datetime对象进行绘图.

日期首先转换为内部浮点格式.转换未设置为处理timedeltas(可以说是一种疏忽).

您基本上可以完全按照自己的意愿行事,您只需要首先将日期明确转换为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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述