14.Django 数据统计

数据统计

echarts: https://echarts.apache.org/examples/zh/index.html#chart-type-bar

# 前端\django\myweb\myweb\urls.py
from django.contrib import admin
from django.urls import path, re_path
# from 前端.django.myweb.blog.test import *
from blog.views import chart

urlpatterns = [
    path('admin/', admin.site.urls),

    # 数据统计
    path('chart/list/', chart.chart_list),
    path('chart/bar/', chart.chart_bar),
    path('chart/pie/', chart.chart_pie),
    path('chart/line/', chart.chart_line),
]
# 前端\django\myweb\blog\views\chart.py
from django.shortcuts import render
from django.http import JsonResponse

# 数据统计
def chart_list(request):
    """数据统计页面"""

    return render(request, 'chart_list.html')

# 数据统计 柱状图 bar
def chart_bar(request):
    """构造柱状图的数据"""

    legend = ['销量', '业绩']
    x_axis = ['1月', '2月', '3月', '4月', '5月', '6月']
    series_list = [
        {
            "name": '销量',
            "type": 'bar',
            "data": [5, 20, 36, 10, 10, 20]
        },
        {
            "name": '业绩',
            "type": 'bar',
            "data": [12, 10, 28, 16, 36, 66]
        }
    ]

    result = {
        "status": True,
        "data": {
            "legend": legend,
            "series_list": series_list,
            "x_axis": x_axis
        }
    }
    return JsonResponse(result)

# 数据统计 饼状图 pie
def chart_pie(request):
    """构造饼状图的数据"""

    db_data_list = [
        {"value": 104, "name": '信息部'},
        {"value": 73, "name": '运营部'},
        {"value": 58, "name": '研发部'},
        {"value": 48, "name": '行政部'},
        {"value": 80, "name": '人事部'}
    ]

    result = {
        "status": True,
        "data": db_data_list
    }

    return JsonResponse(result)

# 数据统计 折线图 line
def chart_line(request):
    """构造饼状图的数据"""

    legend = ['A团队', 'B团队', 'C团队']
    x_axis = ['1月', '2月', '3月', '4月', '5月', '6月']
    series_list = [
        {
            "name": 'A团队',
            "type": 'line',
            "stack": 'TotalA',
            "data": [120, 132, 101, 134, 90, 230, 210]
        },
        {
            "name": 'B团队',
            "type": 'line',
            "stack": 'TotalB',
            "data": [220, 182, 191, 234, 290, 330, 310]
        },
        {
            "name": 'C团队',
            "type": 'line',
            "stack": 'TotalC',
            "data": [189, 220, 150, 190, 300, 180, 398]
        }
    ]

    result = {
        "status": True,
        "data": {
            "legend": legend,
            "series_list": series_list,
            "x_axis": x_axis
        }
    }

    return JsonResponse(result)
<!-- 前端\django\myweb\blog\templates\chart_list.html -->

{% extends 'layout.html' %}

{% block content %}
<div class="container">
  <div class="panel panel-default">
    <div class="panel-heading"><strong>折线图</strong></div>
    <div class="panel-body">
      <div id="m1" style="width: 100%;height:300px;"></div>
    </div>
  </div>
  <div class="row">
    <div class="col-sm-8">
      <div class="panel panel-default">
        <div class="panel-heading"><strong>柱状图</strong></div>
        <div class="panel-body">
          <div id="m2" style="width: 100%;height:400px;"></div>
        </div>
      </div>
    </div>
    <div class="col-sm-4">
      <div class="panel panel-default">
        <div class="panel-heading"><strong>饼状图</strong></div>
        <div class="panel-body">
          <div id="m3" style="width: 100%;height:400px;"></div>
        </div>
      </div>
    </div>

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

echarts.min.js

{% block js %}
{% load static %}
<script src="{% static 'js/echarts.min.js' %}"></script>
{% endblock %}

{% block script %}
<script type="text/javascript">
  $(function () {
    initBar();
    initPie();
    initLine();
  })

  /**
   * 初始化柱状图
   */
  function initLine() {
    var chartDom = document.getElementById('m1');
    var myChart = echarts.init(chartDom);

    var option = {
      title: {
        text: '团队业绩图/万元',
        subtext: '2024上半年度'
      },
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        data: []    // 后端获取
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      toolbox: {
        feature: {
          saveAsImage: {}
        }
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: []    // 后端获取
      },
      yAxis: {
        type: 'value'
      },
      series: []    // 后端获取
    };

    $.ajax({
      url: '/chart/line/',
      type: 'get',
      dataType: 'JSON',
      success: function (res) {
        if (res.status) {
          // 将后台返回的数据更新至option中
          option.legend.data = res.data.legend;
          option.xAxis.data = res.data.x_axis;
          option.series = res.data.series_list;
          // 使用刚指定的配置项和数据显示图表。
          myChart.setOption(option);
        } else {
          alert("获取数据失败!")
        }

      }
    })
  }

  /**
   * 初始化柱状图
   */
  function initBar() {
    // 基于准备好的dom,初始化echarts实例
    // var myChart = echarts.init(document.getElementById('m2'));
    var chartDom = document.getElementById('m2');
    // var myChart = echarts.init(chartDom, 'light');
    var myChart = echarts.init(chartDom);

    // 指定图表的配置项和数据
    var option = {
      title: {
        left: 'center',
        text: '销量/业绩',
        subtext: "2024上半年度",
      },
      tooltip: {},
      legend: {
        orient: 'horizontal',
        bottom: '2%',
        data: []    // 后台获取
      },
      xAxis: {
        data: []    // 后台获取
      },
      yAxis: {},
      series: []    // 后台获取
    };

    $.ajax({
      url: '/chart/bar/',
      type: 'get',
      dataType: 'JSON',
      success: function (res) {
        if (res.status) {
          // 将后台返回的数据更新至option中
          option.legend.data = res.data.legend;
          option.xAxis.data = res.data.x_axis;
          option.series = res.data.series_list;
          // 使用刚指定的配置项和数据显示图表。
          myChart.setOption(option);
        } else {
          alert("获取数据失败!")
        }

      }
    })
  }

  /**
   * 初始化柱状图
   */
  function initPie() {
    var chartDom = document.getElementById('m3');
    var myChart = echarts.init(chartDom);

    var option = {
      title: {
        text: '部门预算占比',
        subtext: '2024年度',
        left: 'center'
      },
      tooltip: {
        trigger: 'item'
      },
      legend: {
        // orient: 'vertical',
        orient: 'horizontal',
        bottom: '2%'
      },
      series: [
        {
          name: '预算/万元',
          type: 'pie',
          radius: '50%',
          data: [],    // 后台获取
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    };

    $.ajax({
      url: '/chart/pie/',
      type: 'get',
      dataType: 'JSON',
      success: function (res) {
        // console.log(res);
        if (res.status) {
          // 将后台返回的数据更新至option中
          option.series[0].data = res.data;
          // 使用刚指定的配置项和数据显示图表。
          myChart.setOption(option);
        } else {
          alert("获取数据失败!")
        }
      }
    })
  }

</script>
{% endblock %}