2011-12-21 135 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