使用 matplotlib 的简单 Django Graph 示例

Pat*_*ick 1 python django matplotlib

我正在寻找一个非常简单的示例,使用 Django QuerySet 然后使用 matplotlib 生成图表。我发现的所有示例都有硬编码的数据值,或者它们并没有真正解释它们在做什么。我认为这对其他人来说也是一个好问题。

让我用一个非常简单的例子来做好准备,这样我和其他 n00bs 就很容易理解。;-)

class Animals(models.Model):
    cats = models.PositiveSmallIntegerField
    dogs = models.PositiveSmallIntegerField
    created = created = models.DateTimeField(auto_now_add=True)

datatograph = Animals.objects.all()
Run Code Online (Sandbox Code Playgroud)

如何将 datatograph 转换为正确的格式,以便将其传递给 matplotlib 并最终得到两个整数的 X 轴、日期的 y 轴以及狗的线和猫的线。

谢谢你!

小智 5

首先让我们创建一些 Animals 对象(我从模型中删除了 auto_now_add 以使其更简单):

from random import randint
from datetime import timedelta
from django.utils import timezone

from animals.models import Animals

animals = []
base_date = timezone.now().replace(day=1)
for i in range(0, 10):
    dt = base_date + timedelta(days=i)
    animals.append(Animals(
        cats=randint(0, 100),
        dogs=randint(0, 100),
        created=dt))

Animals.objects.bulk_create(animals)
Run Code Online (Sandbox Code Playgroud)

然后我们可以做这样的事情:

from django.utils import timezone
from matplotlib import pyplot
from animals.models import Animals

# Fetch the data
begin_date = timezone.now().replace(
    day=1, hour=0, minute=0, second=0, microsecond=0)
end_date = begin_date.replace(day=11)
datatograph = Animals.objects.filter(
    created__gte=begin_date, created__lt=end_date
).values('cats', 'dogs', 'created')

# Transform the data
cats = list(map(lambda d: d['cats'], datatograph))
dogs = list(map(lambda d: d['dogs'], datatograph))
dates = list(map(lambda d: d['created'].day, datatograph))

# Set up the plots
cats_plot = pyplot.plot(dates, cats, 'bo-', label='Cats')[0]
dogs_plot = pyplot.plot(dates, dogs, 'ro-', label='Dogs')[0]

# Set up the axis
pyplot.axis([min(dates), max(dates), min(cats + dogs), max(cats + dogs)])
pyplot.xlabel('day')

# Set up the legend and title
pyplot.legend(handles=[cats_plot, dogs_plot])
pyplot.title('Animals')

# Show the plot
pyplot.show()
Run Code Online (Sandbox Code Playgroud)

这会创建一个像这样的图表。