2012-07-24 59 views
2

使用Python 2.6.2 Matplotlib 1.1.0日期與matplotlib

基於http://matplotlib.sourceforge.net/examples/api/date_index_formatter.html格式化, 我建立了一個Python程序來生成圖像繪圖

gr = getResults() 
AttributeName = gr.getAttributeName(attributeId) 
dates = [] 
values = [] 
for data in gr.byClient(clientId, attributeId): 
    dates.append(data[0]) 
    values.append(data[1]) 

from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas 
from matplotlib.figure import Figure 
import matplotlib.ticker as ticker 
import numpy as np 

# Create a figure with size 6 x 6 inches. 
fig = Figure(figsize=(6,6)) 

# Create a canvas and add the figure to it. 
canvas = FigureCanvas(fig) 

# Create a subplot. 
ax = fig.add_subplot(111) 

# Set the title. 
ax.set_title("Response over time",fontsize=14) 

# Set the X Axis label. 
ax.set_xlabel("Date",fontsize=12) 

# Set the Y Axis label. 
ax.set_ylabel(AttributeName,fontsize=12) 

# Display Grid. 
ax.grid(True,linestyle='-',color='0.75') 

N = len(dates) 
ind = np.arange(N) 

def format_date(x, pos=None): 
    thisind = np.clip(int(x+0.5),0, N-1) 
    return dates[thisind].strftime('%Y-%m-%d') 

ax.xaxis.set_major_formatter(ticker.FuncFormatter(format_date)) 

# Generate the Scatter Plot. 
ax.scatter(dates,values,s=20,color='tomato'); 
fig.autofmt_xdate() 

# Save the generated Scatter Plot to a PNG file. 
canvas.print_figure(outputFileName,dpi=50) 

的問題是在format_date方法。當它被調用時,x參數的值有734586,734747,734808 ...這會導致剪輯方法始終將索引設置爲最後一個日期。最終圖像的實際佈局是好的,它只是選擇了錯誤的日期。如何使用x值來選擇均勻間隔的日期?

回答

6

你可以叫pylab.num2date()這個數字轉換成DateTime對象:

import pylab as pl 
from matplotlib import ticker 
from datetime import date 

dates = [date(2012,7,10), date(2012,8,5), date(2012,9,4)] 
values = [1,2,3] 

def format_date(x, pos=None): 
    return pl.num2date(x).strftime('%Y-%m-%d') 

gca().xaxis.set_major_formatter(ticker.FuncFormatter(format_date)) 

# Generate the Scatter Plot. 
scatter(dates,values,s=20,color='tomato'); 
gcf().autofmt_xdate() 

enter image description here

+0

非常感謝您! – 2012-07-24 05:42:40