1. 前言
使用 Django 进行 Web 开发时,经常有需要展示图表的需求,以此来丰富网页的数据展示
常见方案包含:Highcharts、Matplotlib、Echarts、Pyecharts,其中后 2 种方案使用频率更高
本篇文章将聊聊 Django 结合 Echarts、Pyecharts 实现图表可视化的具体流程
2. Echarts
Echarts 是百度开源的一个非常优秀的可视化框架,它可以展示非常复杂的图表类型
以展示简单的柱状图为例,讲讲 Django 集成 Echarts 的流程
首先,在某个 App 的 views.py 编写视图函数
当请求方法为 POST 时,定义柱状图中的数据值,然后使用 JsonResponse 返回数据
1
|
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
|
{ #导入js和echarts依赖#} <p></p> <p>更多复杂的图表展示可以参考官方</p> <p>https://echarts.apache.org/examples/zh/index.html</p> <h2>3. Pyecharts<br> </h2> <p>Pyecharts 是一款使用 Python 对 Echarts 进行再次封装后的开源框架</p> <p>相比 Echarts,Django 集成 Pyecharts 更快捷、方便</p> <p>Django 集成 Pyecharts 只需要 4 步</p> <h3>3-1 安装依赖</h3> <div class="jb51code"> <pre class="brush:py;"> # 安装依赖 pip(3) install pyecharts</pre> </div> <h3>3-2 拷贝 pyecharts 的模板文件到项目下</h3> <p>将虚拟环境中 pyecharts 的模板文件拷贝到项目的模板文件夹下</p> <p>比如本机路径如下:</p> <p>/Users/xingag/Envs/xh_log/lib/python3.7/site-packages/pyecharts/render/templates/</p> <p><img src="https://img.php1.cn/3cd4a/3e52/b64/3a04a76a5d13c587.png&#63;202138142519" alt=""></p> <h3>3-3 编写视图函数,渲染图表</h3> <p>在视图文件中,使用 pyecharts 库内置的类 Bar 创建一个柱状图</p> <div class="jb51code"> <pre class="brush:py;"> # 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())</pre> </div> <h3>3-4 运行项目</h3> <p>运行项目,生成的柱状图如下:</p> <p><img src="https://img.php1.cn/3cd4a/3e52/b64/15b8421eb6d10082.png&#63;202138142614" alt=""></p> <p>这只是最简单的使用实例,更多复杂的图表及前后端分离、更新的例子</p> <p>可以参考官网:</p> <p>https://pyecharts.org/#/zh-cn/web_django&#63;id=django-前后端分离</p> <h2>4. 最后<br> </h2> <p>文中介绍了 Django 快速集成 Echarts 和 Pyecharts 的基本步骤</p> <p>实际项目中,一些复杂的图表、前后端分离数据更新可以参考官网去拓展</p> <p>源码:https://github.com/xingag/python_web</p> <p>以上就是Django展示可视化图表的多种方式的详细内容,更多关于Django 可视化图表的资料请关注其它相关文章!</p> 内容推荐:<a href="https://www.pngbox.cn" target="_blank" title="免费高清PNG素材下载">免费高清PNG素材下载</a> |
文章来源于网络,如有侵权请联系本站管理人员处理