1. 前言
大家好场靴,我是安果啡莉!
使用 Django 進行 Web 開發(fā)時,經(jīng)常有需要展示圖表的需求旨剥,以此來豐富網(wǎng)頁的數(shù)據(jù)展示
常見方案包含:Highcharts咧欣、Matplotlib、Echarts轨帜、Pyecharts魄咕,其中后 2 種方案使用頻率更高
本篇文章將聊聊 Django 結合 Echarts、Pyecharts 實現(xiàn)圖表可視化的具體流程
2. Echarts
Echarts 是百度開源的一個非常優(yōu)秀的可視化框架蚌父,它可以展示非常復雜的圖表類型
以展示簡單的柱狀圖為例哮兰,講講 Django 集成 Echarts 的流程
首先,在某個 App 的 views.py 編寫視圖函數(shù)
當請求方法為 POST 時苟弛,定義柱狀圖中的數(shù)據(jù)值喝滞,然后使用 JsonResponse 返回數(shù)據(jù)
from django.http import JsonResponse
from django.shortcuts import render
def index_view(request):
if request.method == "POST":
# 柱狀圖的數(shù)據(jù)
datas = [5, 20, 36, 10, 10, 20]
# 返回數(shù)據(jù)
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 函數(shù)右遭,發(fā)送一個 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)
}
//顯示即加載調(diào)用
window.onload = function () {
//發(fā)送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),
]
發(fā)現(xiàn)亭敢,首頁展示了一個簡單的柱狀圖
更多復雜的圖表展示可以參考官方
https://echarts.apache.org/examples/zh/index.html
3. Pyecharts
Pyecharts 是一款使用 Python 對 Echarts 進行再次封裝后的開源框架
相比 Echarts滚婉,Django 集成 Pyecharts 更快捷、方便
Django 集成 Pyecharts 只需要 4 步
3-1 安裝依賴
# 安裝依賴
pip(3) install pyecharts
3-2 拷貝 pyecharts 的模板文件到項目下
將虛擬環(huán)境中 pyecharts 的模板文件拷貝到項目的模板文件夾下
比如本機路徑如下:
/Users/xingag/Envs/xh_log/lib/python3.7/site-packages/pyecharts/render/templates/
3-3 編寫視圖函數(shù)帅刀,渲染圖表
在視圖文件中让腹,使用 pyecharts 庫內(nèi)置的類 Bar 創(chuàng)建一個柱狀圖
# 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 運行項目
運行項目远剩,生成的柱狀圖如下:
這只是最簡單的使用實例,更多復雜的圖表及前后端分離哨鸭、更新的例子
可以參考官網(wǎng):
https://pyecharts.org/#/zh-cn/web_django?id=django-%e5%89%8d%e5%90%8e%e7%ab%af%e5%88%86%e7%a6%bb
4. 最后
文中介紹了 Django 快速集成 Echarts 和 Pyecharts 的基本步驟
實際項目中民宿,一些復雜的圖表娇妓、前后端分離數(shù)據(jù)更新可以參考官網(wǎng)去拓展
我已經(jīng)將文中完整代碼上傳到后臺像鸡,關注公眾號「 AirPython 」后,回復關鍵字「 210406 」獲取
如果你覺得文章還不錯哈恰,請大家 點贊只估、分享、留言 下着绷,因為這將是我持續(xù)輸出更多優(yōu)質文章的最強動力蛔钙!