脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Django展示可视化图表的多种方式

Django展示可视化图表的多种方式

2021-10-07 00:18AirPython Python

这篇文章主要介绍了Django展示可视化图表的多种方式,帮助大家更好的理解和学习使用django框架,感兴趣的朋友可以了解下

1. 前言

大家好,我是安果!

使用 django 进行 web 开发时,经常有需要展示图表的需求,以此来丰富网页的数据展示

常见方案包含:highcharts、matplotlib、echarts、pyecharts,其中后 2 种方案使用频率更高

本篇文章将聊聊 django 结合 echarts、pyecharts 实现图表可视化的具体流程

2. echarts

echarts 是百度开源的一个非常优秀的可视化框架,它可以展示非常复杂的图表类型

以展示简单的柱状图为例,讲讲 django 集成 echarts 的流程

首先,在某个 app 的 views.py 编写视图函数

当请求方法为 post 时,定义柱状图中的数据值,然后使用 jsonresponse 返回数据

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
from django.http import jsonresponse
from django.shortcuts import render
 
 
def index_view(request):
    if request.method == "post":
 
        # 柱状图的数据
        datas = [5, 20, 36, 10, 10, 20]
 
        # 返回数据
        return jsonresponse({'bar_datas': datas})
    else:
        return render(request, 'index.html', )

在模板文件中,导入 echarts 的依赖

ps:可以使用本地 js 文件或 cdn 加速服务

?
1
2
3
{#导入js和echarts依赖#}
<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>

然后,重写 window.onload 函数,发送一个 ajax 请求给后端,利用 echarts 将返回结果展示到图表中去

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
​<script>
    // 柱状图
    function show_bar(data) {
 
        //控件
        var bar_widget = echarts.init(document.getelementbyid('bar_div'));
 
        //设置option
        option = {
            title: {
                text: '简单的柱状图'
            },
            tooltip: {},
            legend: {
                data: ['销量']
            },
            xaxis: {
                type: 'category',
                data: ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]
            },
            yaxis: {
                type: 'value'
            },
            series: [{
                data: data,
                type: 'bar'
            }]
        };
 
        bar_widget.setoption(option)
    }
    //显示即加载调用
    window.onload = function () {
        //发送post请求,地址为index(jquery)
        $.ajax({
            url: "/",
            type: "post",
            data: {},
            success: function (data) {
                // 柱状图
                show_bar(data['bar_datas']);
 
                //后端返回的结果
                console.log(data)
            }
        })
    }
</script>

最后,编写路由 url,运行项目

?
1
2
3
4
5
6
7
from django.contrib import admin
from django.urls import path, include
 
urlpatterns = [
    path('',include('index.urls')),
​    path('admin/', admin.site.urls),
]

发现,首页展示了一个简单的柱状图

Django展示可视化图表的多种方式

更多复杂的图表展示可以参考官方

https://echarts.apache.org/examples/zh/index.html

3. pyecharts

pyecharts 是一款使用 python 对 echarts 进行再次封装后的开源框架

相比 echarts,django 集成 pyecharts 更快捷、方便

django 集成 pyecharts 只需要 4 步

3-1  安装依赖

?
1
2
# 安装依赖
pip(3) install pyecharts

3-2  拷贝 pyecharts 的模板文件到项目下

将虚拟环境中 pyecharts 的模板文件拷贝到项目的模板文件夹下

比如本机路径如下:

/users/xingag/envs/xh_log/lib/python3.7/site-packages/pyecharts/render/templates/

Django展示可视化图表的多种方式

3-3  编写视图函数,渲染图表

在视图文件中,使用 pyecharts 库内置的类 bar 创建一个柱状图

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# create your views here.
from django.http import httpresponse
from jinja2 import environment, filesystemloader
from pyecharts.globals import currentconfig
 
currentconfig.global_env = environment(loader=filesystemloader("./index/templates"))
 
from pyecharts import options as opts
from pyecharts.charts import bar
 
 
# http://127.0.0.1:8000/demo/
def index(request):
    c = (
        bar()
            .add_xaxis(["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"])
            .add_yaxis("商家a", [5, 20, 36, 10, 75, 90])
            .add_yaxis("商家b", [15, 25, 16, 55, 48, 8])
            .set_global_opts(title_opts=opts.titleopts(title="bar-基本示例", subtitle="我是副标题"))
    )
    return httpresponse(c.render_embed())

3-4  运行项目

运行项目,生成的柱状图如下:

Django展示可视化图表的多种方式

这只是最简单的使用实例,更多复杂的图表及前后端分离、更新的例子

可以参考官网:

https://pyecharts.org/#/zh-cn/web_django?id=django-前后端分离

4. 最后

文中介绍了 django 快速集成 echarts 和 pyecharts 的基本步骤

实际项目中,一些复杂的图表、前后端分离数据更新可以参考官网去拓展

源码:https://github.com/xingag/python_web

以上就是django展示可视化图表的多种方式的详细内容,更多关于django 可视化图表的资料请关注服务器之家其它相关文章!

原文链接:https://www.cnblogs.com/xingag/p/14631278.html

延伸 · 阅读

精彩推荐