Django图表 - 日期和时间轴

时间:2011-04-15 09:18:24

标签: django charts django-views

我有一个看起来像这样的模型:

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

但是,我希望横轴显示日期和时间(保存在模型中)。有谁知道怎么做?

1 个答案:

答案 0 :(得分: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他们。
  3. 例如:

    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))
    

    如果您无法执行具体细节,请随意打开另一个问题。