Django绘制饼状图

首先他的官网是:https://echarts.apache.org/examples/zh/index.html#chart-type-pie

官方开发文档:https://echarts.apache.org/handbook/zh/get-started/

 

在Django中实现

首先看实现效果

图片[1]-Django绘制饼状图-Djiango论坛-Python编程-青柠博客

 

配置文件urls.py

from django.urls import path
from user import views
urlpatterns = [
# path('admin/', admin.site.urls),
path('',views.index),
path('index_api',views.index_api)
]

编写视图views.py

from django.shortcuts import render,HttpResponse
from django.http import JsonResponse
# Create your views here.
def index(request):
    
        return render(request, 'index.html', )
def index_api(request):
    if request.method == "POST":
       
        data={ 'value': 1048, 'name': 'Search Engine' },{ 'value': 735, 'name': 'Direct' },{' value': 580, 'name': 'Email' },{ 'value': 484, 'name': 'Union Ads' },{ 'value': 300, 'name': 'Video Ads' }

        # 返回数据
        return JsonResponse({'bar_datas': data})
    else:
        return render(request, 'index.html', )

编写模板index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="js-chartjs-bars" name="js-chartjs-bars" style=" width: calc(96vw - 50px);height: calc(96vh - 50px);"></div>  
</body>



<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/echarts/5.0.2/echarts.common.js"></script>
<script type="text/javascript">

</script>
<script>    // 柱状图
    function show_bar(data) {
    
    //控件
    var bar_widget = echarts.init(document.getElementById('js-chartjs-bars'));
   
    
    //设置option
    option = {
  title: {
    text: '库存预警',
    subtext: 'Fake Data',
    left: 'center'
  },
  tooltip: {
    trigger: 'item'
  },
  legend: {
    orient: 'vertical',
    left: 'left'
  },
  series: [
    {
      name: 'Access From',
      type: 'pie',
      radius: '50%',
      data: data,
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }
  ]
};
    
    bar_widget.setOption(option)
        }
    
    //显示即加载调用
    window.onload = function () {
    //发送post请求,地址为index(Jquery)
    $.ajax({
    url: "index_api",
    type: "POST",
    data: {},
    success: function (data) {
    // 柱状图
    show_bar(data['bar_datas']);
    
    
    //后端返回的结果
    console.log(data)
                }
            })
        }

  

</script>
</html>

 

 

请登录后发表评论

    没有回复内容