2012-03-09 112 views
36

我想繪製日期信息。我有一個格式爲「01/02/1991」的日期列表。使用Python的matplotlib繪製x軸上的日期

我做轉換它們如下:

x = parser.parse(date).strftime('%Y%m%d')) 

這給19910102

然後我試圖使用num2date

import matplotlib.dates as dates 
new_x = dates.num2date(x) 

繪圖:

plt.plot_date(new_x, other_data, fmt="bo", tz=None, xdate=True) 

但是我得到一個錯誤。它說「ValueError:年度超出範圍」。任何解決方案

+0

啊,我給了一個壞榜樣日期。我實際上沒有在我的日期列表中2012年12月31日。我已將它更改爲1991年1月2日。 – 2012-03-09 01:49:02

+1

help(num2date):「x是一個浮點值,它給出加上自0001-01-01以來的天數」,因此x = 19910102不對應於1991年1月2日 – 2012-03-09 01:51:14

回答

14

正如@KyssTao一直在說的,help(dates.num2date)表示x必須是自0001-01-01加1後的天數。因此,19910102不是2/Jan/1991,因爲如果你從0001-01-01算起19910101天,你會得到54513年或類似的東西(除以365.25,一年中的天數)。

使用datestr2num代替(見help(dates.datestr2num)):

new_x = dates.datestr2num(date) # where date is '01/02/1991' 
76

你可以做的plot_date()這更簡單的使用plot()代替。

首先,將您的字符串實例的Python datetime.date的:

import datetime as dt 

dates = ['01/02/1991','01/03/1991','01/04/1991'] 
x = [dt.datetime.strptime(d,'%m/%d/%Y').date() for d in dates] 
y = range(len(x)) # many thanks to Kyss Tao for setting me straight here 

然後劇情:

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

plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%m/%d/%Y')) 
plt.gca().xaxis.set_major_locator(mdates.DayLocator()) 
plt.plot(x,y) 
plt.gcf().autofmt_xdate() 

結果:

enter image description here

+0

您可以只寫y = range(len(x)) – 2012-03-09 02:43:24

+0

我只知道可以使用xrange()來避免創建列表;但是在這裏我們創建了一個列表 – 2012-03-09 03:40:39

+0

我只是用len(x)做了一個時間實驗,是10Mio。我期望range()和你的列表理解與xrange()一樣長;但令我驚訝的範圍()更快! – 2012-03-09 03:46:12