1. 前言

大家好,我是安果!

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

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

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

2. echarts

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

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

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

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

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 加速服务

{#导入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 将返回结果展示到图表中去

​<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,运行项目

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('',include('index.urls')),
​    path('admin/', admin.site.urls),
]

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

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

3. pyecharts

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

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

django 集成 pyecharts 只需要 4 步

3-1  安装依赖

# 安装依赖
pip(3) install pyecharts

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

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

比如本机路径如下:

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

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

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

# 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  运行项目

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

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

可以参考官网:

-前后端分离

4. 最后

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

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

源码:

以上就是django展示可视化图表的多种方式的详细内容,更多关于django 可视化图表的资料请关注www.887551.com其它相关文章!