2011-04-15 123 views
0

我有一個模型,它看起來像這樣:Django的圖表 - 日期和時間軸

class Measurement(models.Model): 
    date = models.DateField('date') 
    time = models.TimeField('time') 
    Q = models.DecimalField(max_digits=10, decimal_places=6) 
    P = models.DecimalField(max_digits=10, decimal_places=6) 
    f = models.DecimalField(max_digits=10, decimal_places=6) 

在我的意見,我謹代表它。所以我做了這個功能:

def plotMeas(request):  

    # Count the events 
    c = Measurement.objects.all() 
    c = c.count() 

    # Variables 
    i = 0 
    a = [0] 
    P = a*c 
    Q = a*c 
    t = a*c 

    # Save dP_L1 & dQ_L1 in lists 
    for i in range(c): 
     meas = Measurement.objects.get(pk = i+1) 
     P [i] = meas.P 
     Q [i] = meas.Q 
     t [c-1-i] = i*10 

    if c > 100: 
     P = P[-100:] 
     Q = Q[-100:] 
     t [i] = t[-100:] 

    # Construct the graph 
    fig = Figure() 
    q = fig.add_subplot(211) 

    q.set_xlabel("time (minutes ago)") 
    q.set_ylabel("Q (VAR)") 

    p = fig.add_subplot(212) 

    p.set_xlabel("time (minutes ago)") 
    p.set_ylabel("P (W)") 

    p.plot(t,P, 'go-') 
    q.plot(t,Q, 'o-') 

    canvas = FigureCanvas(fig) 
    response = HttpResponse(content_type='image/png') 

    canvas.print_png(response) 
    return response 

但是,我想水平軸將顯示日期和時間(保存在模型中)。有誰知道該怎麼做?

回答

0

查看plot_date的文檔。方便plot_date採取類似的論點plot。呼叫可能看起來像:

p.plot_date(sequence_of_datetime_objects, y_axis_values, 'go-') 

使用matplotlib.dates那麼你可以定製你的x軸標籤的格式。
一個簡單的例子:
以下將指定x軸以格式Jan '09(假設說英語的語言環境)每三個月顯示一次。

p.xaxis.set_major_locator(mdates.MonthLocator(interval=3)) 
p.xaxis.set_major_formatter(mdates.DateFormatter("%b '%y")) 

既然你有日期和時間分開存放,你既可以想

  1. 變化模型使用DateTimeField,或
  2. 使用Python combine他們。

例如:

import datetime as dt 
t1 = dt.time(21,0,1,2) # 21:00:01.2 
d1 = dt.date.today() 
dt1 = dt.datetime.combine(d1,t1) 
# result: datetime.datetime(2011, 4, 15, 21, 0, 1, 2) 

遍歷兩個序列,並結合他們,你可能會使用zip(代碼僅用於說明目的,不一定是優化):

sequence_of_datetime_objects = [] 
for a_date, a_time in zip(sequence_of_date_objects, sequence_of_time_objects): 
    sequence_of_datetime_objects.append(dt.datetime.combine(a_date, a_time)) 

隨意如果您在實施細節時遇到問題,請打開另一個問題。