如何使用Python字典数据和Morris来制作线图?

2024-04-23 18:27:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着做一个折线图,显示一个财政年度每天登记入住的人数。当我用虚拟数据创建图形时,它是有效的。但是当我使用实际数据时,我很难让图表正常工作。我正在尝试使用Counts字典中的数据,因为它包含签入者的日期和相应计数。你知道吗

我曾尝试使用for语句来获取counts中的一个项,但图形最终为空。我也试过用for语句来抓住每一天count.日期迭代不同的日期并获取特定日期的数据,但这也导致了一个空白图。你知道吗

索引_图形.html你知道吗

{% extends "admin/base_site.html" %}
{% load static %}
{% load i18n %}
{% load in_group %}

{% block extrastyle %}
    <link type='text/css' rel='stylesheet' href="{% static 'index.css' %}">
{% endblock %}

{% block content %}
<div class="row-fluid">
    <div class="span12 text-center" id="pdfRenderer" style="width: 80%; align: left;">

        <script src="{% static 'js/raphael-min.js' %}"></script>
        <script src="{% static 'js/morris-0.4.3.min.js' %}"></script>
        <link rel="stylesheet" href="{% static 'css/morris-0.4.3.min.css' %}">

        <h5>Swipe Data from {{fiscal_start_date}} to {{fiscal_end_date}}</h5>

    <div id="line-graph">
      <script>
        var count = {{counts}}
        new Morris.Line({
          element: 'line-graph',

          data: [
          {% for day in count.dates %}
          {date: {{day.day }}, count: {{day.counts}} }
          {% endfor %},
          ],

        xkey: 'date', //the name of data attribute containing x-values
        ykeys: ['count'], //the name of data attribute containing y-values

        lineColors: ['#840A00'],

        })
       </script>

    </div>
</div>
{% endblock %}

<!-- Sidebar -->
{% block sidebar %}

    {% include "partcount/fac_sidebar.html" %}

{% endblock %}

你知道吗视图.py你知道吗

class Index(TemplateView):

    @user_is_authenticated
    def dispatch(self, request, *args, **kwargs):
        return super(Index, self).dispatch(request, *args, **kwargs)

    template_name = "partcount/index_graph.html"

    def get_context_data(self, **kwargs):
        context = super(Index, self).get_context_data(**kwargs)

        now = datetime.now()
        if now.month < 7:
            last_year = now.year - 2
        else:
            last_year = now.year - 1
        july1 = datetime(year=last_year, month=7, day=1)

        if now.month < 6:
            year = now.year - 1  # Always want to use the prior year after new year
        else:
            year = now.year
        june30 = datetime(year=year, month=6, day=30)

        counts = UserCount.get_daily_counts(july1.date(),june30.date())

        context['title'] = 'Facilities'
        context['fiscal_start_date']= july1.date()
        context['fiscal_end_date']= june30.date()
        context['count'] = counts

        num_males = ParticipationCount.objects.aggregate(Sum('male'))['male__sum']
        num_females = ParticipationCount.objects.aggregate(Sum('female'))['female__sum']

        if num_males and num_females:
            total = float(num_males + num_females)
            context['male_percent'] = num_males/total*100
            context['female_percent'] = num_females/total*100

            return context

你知道吗型号.py你知道吗

import redis
import datetime
import json

from django.db import models

from urec.settings import REDIS_HOST, REDIS_DB


class UserCount(object):

    @staticmethod
    def get_daily_counts(start_date, end_date, profitcenter_id=7):

        r = redis.Redis(host=REDIS_HOST, db=REDIS_DB)

        n_days = (end_date - start_date).days

        dates = [start_date + datetime.timedelta(days=i) for i in range(n_days)] # list of dates in range

        counts = []
        for date in dates:
            r_key = 'urec:counts:%s:%s' % (profitcenter_id,str(date))
            member_counts = r.get(r_key)
            if member_counts:
                member_counts = json.loads(member_counts)
                entry = {'date': date, 'counts': member_counts}
                counts.append(entry)

        # now counts has the form [{'date':date, 'counts': {membertype1: count1, ...}},...]

        return counts

Tags: indivfordatadatecountcontextscript