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

时间:2012-06-14 22:36:02

标签: python datetime matplotlib bar-chart

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

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

但是这会在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       orientation ='horizo​​ntal',** kwargs)     文件“/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/axes.py”,第4624行,在栏中       width = self.convert_xunits(width)     在convert_xunits中输入文件“/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/artist.py”,第147行       返回ax.xaxis.convert_units(x)     在convert_units中输入文件“/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行,在转换       return date2num(value)     在date2num中输入文件“/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/dates.py”,第260行       else:return np.asarray([_ to_ordinalf(val)for val in d])     在_to_ordinalf中输入文件“/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/dates.py”,第189行       base = float(dt.toordinal())

     

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

我认为如果我能把日期时间推到xaxis并拥有它,那就太好了 弄清楚细节;没那么多。关于如何使日期与xaxis相关的任何建议?

1 个答案:

答案 0 :(得分:14)

正在发生的事情是matplotlib实际上并没有使用日期时间对象进行绘图。

日期首先转换为内部浮点格式。转换没有设置为处理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()

enter image description here