Django图表-日期和时间轴
我有一个模型如下所示:Django图表-日期和时间轴,django,charts,django-views,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 = mod
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
但是,我希望横轴显示模型中保存的日期和时间。有人知道怎么做吗?请查看有关的文档。方便地,plot_date采用与plot类似的参数。一个电话可能看起来像:
p.plot_date(sequence_of_datetime_objects, y_axis_values, 'go-')
然后可以使用自定义x轴标签的格式。
一个简单的例子:
以下内容将指定x轴仅每隔三个月显示一次,格式为2009年1月(假设使用英语区域设置)
p.xaxis.set_major_locator(mdates.MonthLocator(interval=3))
p.xaxis.set_major_formatter(mdates.DateFormatter("%b '%y"))
因为日期和时间是分开存储的,所以您可以选择
将模型更改为使用,或
使用Python来创建它们。
例如:
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)
要在两个序列上迭代并组合它们,您可以仅将代码用于说明目的,而不必进行优化:
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))
如果你在具体实施过程中遇到困难,请随时提出另一个问题