2011-12-21 26 views
0

我想使用条形图在y轴上绘制日期时间并在x轴上绘制时间。我需要根据Y轴的日期时间来指定高度,我不知道该怎么做。这个matplotlib代码有什么问题?

import matplotlib.pyplot as plt 
import matplotlib as mpl 
import numpy as np 
import datetime as dt 

# Make a series of events 1 day apart 
y = mpl.dates.drange(dt.datetime(2009,10,1), 
       dt.datetime(2010,1,15), 
       dt.timedelta(days=1)) 
# Vary the datetimes so that they occur at random times 
# Remember, 1.0 is equivalent to 1 day in this case... 
y += np.random.random(x.size) 

# We can extract the time by using a modulo 1, and adding an arbitrary base date 
times = y % 1 + int(y[0]) # (The int is so the y-axis starts at midnight...) 

# I'm just plotting points here, but you could just as easily use a bar. 
fig = plt.figure() 
ax = fig.add_subplot(111) 
ax.bar(times, y, width = 10) 

ax.yaxis_date() 
fig.autofmt_ydate() 

plt.show() 

回答

0

我认为这可能是你的y范围。 当我做你的代码时,我得到一个y轴约11/Dec/2011至21/Dec/2011的情节。

但是,您生成的日期范围从1/10/2009到2010年1月15日。

当我调整我的y限制以考虑到这一点时,它工作正常。我在ax.bar之后加了这个。

plt.ylim((min(y)-1,max(y)+1)) 

另一个原因输出困惑的是,既然你选择了10的宽度,酒吧太宽,实际上是混淆彼此。

尝试使用ax.plot(times,y,'ro')来看看我的意思。

我产生了以下情节使用ax.bar(times,y,width=.1,alpha=.2)ax.plot(times,y,'ro')向你展示我的意思大约条相互重叠: enter image description here

而这与.1条的宽度,因此,如果他们有一个宽度10他们会完全模糊对方。

+0

mod date带1会给你个别时间 – 2011-12-21 01:54:14

+0

问题好像是bar中的高度参数。我不知道你如何提供日期时间为高度 – 2011-12-21 01:55:08

+0

啊,我同意。对于我的第一个答案感到抱歉:你应该有'+ = np.random.random(y.size)'而不是'x.size'。起初,我没有注意到所导致的错误,所以我的'y'最终成为一串整数,当你做一个'%1'时,这当然会给出'0'。我已经更新了我对问题的解答。 – 2011-12-21 02:27:33