1. 下载pyecharts
pip install pyecharts
2.创建app
python manage.py startapp pyechart_demo
3. 注册app
- 位置:在django_test/settings.py注册
4.配置新app的urls
-
新建urls.py
-
编写代码,配置view文件
-
在django_test/urls.py中配置
5. 使用pyecharts模板
- 将位于pyecharts.render.templates 拷贝至刚新建的 templates 文件夹
- 复制到这个位置
6. 渲染图表
- 模板官网:https://gallery.pyecharts.org/#/Parallel/basic_parallel
- 将下列代码保存到 pyechart_demo/views.py 中
from django.shortcuts import render
# Create your views here.
from jinja2 import Environment, FileSystemLoader
from pyecharts.globals import CurrentConfig
from django.http import HttpResponse
CurrentConfig.GLOBAL_ENV = Environment(loader=FileSystemLoader("./pyechart_demo/templates"))
from pyecharts import options as opts
from pyecharts.charts import Bar
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())
从原始模板复制过来,需要将.render("basic_parallel.html")删除,并加上return HttpResponse(c.render_embed())
7. 运行项目
- 打开服务器
python manage.py runserver
- 输入网址:http://127.0.0.1:8000/pyechart_demo/
- 效果: