Several methods of dynamic display of pychart data by Django

Python Programming and Practice 2020-11-16 20:32:51
methods dynamic display pychart data


This article will show you how to web frame Django Using visualization tools in Pyecharts, After reading this tutorial, you will learn several ways to dynamically display visual data !

Django Template rendering

1. Create a new one Django project

Enter the following command on the command line

django-admin startproject pyecharts_django_demo

Create an application

python manage.py startapp demo

After creation , stay Pycharm Open the project , Of course, you can also go directly to Pycharm Created in

At the same time pyecharts_django_demo/settings.py Register application in INSTALLED_APPS Add application to demo

stay pyecharts_django_demo/urls.py Newly added demo.urls

2. New projects urls file

edit demo/urls.py file , If not, create a new one

from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^pie/$', views.ChartView.as_view(), name='demo'),
url(r'^index/$', views.IndexView.as_view(), name='demo'),
]

3. To write Django and pyecharts Code rendering diagram

because json The problem with data types , Cannot be pyecharts Medium JSCode Type of data to json Data format back to the front page to use .

Therefore, in the case of using front and rear separation, try to avoid the use of JSCode Drawing .

Save the following code to demo/views.py in

from django.shortcuts import render
# Create your views here.
import json
from random import randrange
from django.http import HttpResponse
from rest_framework.views import APIView
from pyecharts.charts import Bar, Pie
from pyecharts.faker import Faker
from pyecharts import options as opts
# Create your views here.
def response_as_json(data):
json_str = json.dumps(data)
response = HttpResponse(
json_str,
content_type="application/json",
)
response["Access-Control-Allow-Origin"] = "*"
return response
def json_response(data, code=200):
data = {
"code": code,
"msg": "success",
"data": data,
}
return response_as_json(data)
def json_error(error_string="error", code=500, **kwargs):
data = {
"code": code,
"msg": error_string,
"data": {}
}
data.update(kwargs)
return response_as_json(data)
JsonResponse = json_response
JsonError = json_error
def pie_base() -> Pie:
c = (
Pie()
.add("", [list(z) for z in zip(Faker.choose(), Faker.values())])
.set_colors(["blue", "green", "yellow", "red", "pink", "orange", "purple"])
.set_global_opts(title_opts=opts.TitleOpts(title="Pie- Example "))
.set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {c}"))
.dump_options_with_quotes()
)
return c
class ChartView(APIView):
def get(self, request, *args, **kwargs):
return JsonResponse(json.loads(pie_base()))
class IndexView(APIView):
def get(self, request, *args, **kwargs):
return HttpResponse(content=open("./templates/index.html").read())

4. Drawing HTML Code

Create a new... In the root directory templates Folder , And create a new index.html file

index.html

The code is as follows :

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Awesome-pyecharts</title>
<script src="https://cdn.bootcss.com/jquery/3.0.0/jquery.min.js"></script>
<script type="text/javascript" src="https://assets.pyecharts.org/assets/echarts.min.js"></script>
</head>
<body>
<div id="pie" style="width:1000px; height:600px;"></div>
<script>
var chart = echarts.init(document.getElementById('pie'), 'white', {renderer: 'canvas'});
$(
function () {
fetchData(chart);
}
);
function fetchData() {
$.ajax({
type: "GET",
url: "http://127.0.0.1:8000/demo/pie",
dataType: 'json',
success: function (result) {
chart.setOption(result.data);
}
});
}
</script>
</body>
</html>

After running , Open it in a browser , The effect is as follows :

Update charts regularly and in full

This is a static data display method , use Pyecharts and Django Combination is mainly to achieve a dynamic update of data , Incremental update data and other functions !

Timing full update is mainly the front-end and back-end data refresh , The core of regular refresh is HTML Of setInterval Method .

that index.html This is the code :

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Awesome-pyecharts</title>
<script src="https://cdn.bootcss.com/jquery/3.0.0/jquery.min.js"></script>
<script type="text/javascript" src="https://assets.pyecharts.org/assets/echarts.min.js"></script>
</head>
<body>
<div id="bar" style="width:1600px; height:800px;"></div>
<script>
var chart = echarts.init(document.getElementById('bar'), 'white', {renderer: 'canvas'});
$(
function () {
fetchData(chart);
setInterval(fetchData, 100);
}
);
function fetchData() {
$.ajax({
type: "GET",
url: "http://127.0.0.1:8000/demo/bar",
dataType: 'json',
success: function (result) {
chart.setOption(result.data);
}
});
}
</script>
</body>
</html>

At the same time demo/views.py in , Add and modify code :

views.py

demo/urls.py in , Add the following code :

urlpatterns = [
url(r'^pie/$', views.ChartView.as_view(), name='demo'),
url(r'^bar/$', views.ChartView.as_view(), name='demo'),
url(r'^index/$', views.IndexView.as_view(), name='demo'),
]

After running , The effect is as follows :

Post a picture that I made before ( Because I am lazy ), The effect is the same as above

Regular incremental update chart

The principle is the same , First modify index.html , The code is as follows :

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Awesome-pyecharts</title>
<script src="https://cdn.bootcss.com/jquery/3.0.0/jquery.min.js"></script>
<script type="text/javascript" src="https://assets.pyecharts.org/assets/echarts.min.js"></script>
</head>
<body>
<div id="bar" style="width:1600px; height:800px;"></div>
<script>
var chart = echarts.init(document.getElementById('bar'), 'white', {renderer: 'canvas'});
var old_data = [];
$(
function () {
fetchData(chart);
setInterval(fetchData, 2000);
}
);
function fetchData() {
$.ajax({
type: "GET",
url: "http://127.0.0.1:8000/demo/line",
dataType: "json",
success: function (result) {
var options = result.data;
chart.setOption(options);
old_data = chart.getOption().series[0].data;
}
});
}
function getDynamicData() {
$.ajax({
type: "GET",
url: "http://127.0.0.1:8000/demo/lineUpdate",
dataType: 'json',
success: function (result) {
var options = result.data;
old_data.push([options.name, options.value]);
chart.setOption({
series: [{
data: old_data
}]
});
}
});
}
</script>
</body>
</html>

Careful you should be able to find , There are two new request addresses demo/line, demo/lineUpdate

so, stay urlpatterns Add the following path matching in

url(r'^line/$', views.ChartView.as_view(), name='demo'),
url(r'^lineUpdate/$', views.ChartView.as_view(), name='demo'),

Last in views.py Add the following code :

def line_base() -> Line:
line = (
Line()
.add_xaxis(["{}".format(i) for i in range(10)])
.add_yaxis(
series_name="",
y_axis=[randrange(50, 80) for _ in range(10)],
is_smooth=True,
label_opts=opts.LabelOpts(is_show=False),
)
.set_global_opts(
title_opts=opts.TitleOpts(title=" Dynamic data "),
xaxis_opts=opts.AxisOpts(type_="value"),
yaxis_opts=opts.AxisOpts(type_="value"),
)
.dump_options_with_quotes()
)
return line
class ChartView(APIView):
def get(self, request, *args, **kwargs):
return JsonResponse(json.loads(line_base())
cnt = 9
class ChartUpdateView(APIView):
def get(self, request, *args, **kwargs):
global cnt
cnt = cnt + 1
return JsonResponse({"name": cnt, "value": randrange(0, 100)})

Run and open , The effect is as follows :

This article is from WeChat official account. - Python Programming and Practice (GoPy1024) , author :Jerryning

The source and reprint of the original text are detailed in the text , If there is any infringement , Please contact the yunjia_community@tencent.com Delete .

Original publication time : 2020-11-11

Participation of this paper Tencent cloud media sharing plan , You are welcome to join us , share .

版权声明
本文为[Python Programming and Practice]所创,转载请带上原文链接,感谢

  1. 利用Python爬虫获取招聘网站职位信息
  2. Using Python crawler to obtain job information of recruitment website
  3. Several highly rated Python libraries arrow, jsonpath, psutil and tenacity are recommended
  4. Python装饰器
  5. Python实现LDAP认证
  6. Python decorator
  7. Implementing LDAP authentication with Python
  8. Vscode configures Python development environment!
  9. In Python, how dare you say you can't log module? ️
  10. 我收藏的有关Python的电子书和资料
  11. python 中 lambda的一些tips
  12. python中字典的一些tips
  13. python 用生成器生成斐波那契数列
  14. python脚本转pyc踩了个坑。。。
  15. My collection of e-books and materials about Python
  16. Some tips of lambda in Python
  17. Some tips of dictionary in Python
  18. Using Python generator to generate Fibonacci sequence
  19. The conversion of Python script to PyC stepped on a pit...
  20. Python游戏开发,pygame模块,Python实现扫雷小游戏
  21. Python game development, pyGame module, python implementation of minesweeping games
  22. Python实用工具,email模块,Python实现邮件远程控制自己电脑
  23. Python utility, email module, python realizes mail remote control of its own computer
  24. 毫无头绪的自学Python,你可能连门槛都摸不到!【最佳学习路线】
  25. Python读取二进制文件代码方法解析
  26. Python字典的实现原理
  27. Without a clue, you may not even touch the threshold【 Best learning route]
  28. Parsing method of Python reading binary file code
  29. Implementation principle of Python dictionary
  30. You must know the function of pandas to parse JSON data - JSON_ normalize()
  31. Python实用案例,私人定制,Python自动化生成爱豆专属2021日历
  32. Python practical case, private customization, python automatic generation of Adu exclusive 2021 calendar
  33. 《Python实例》震惊了,用Python这么简单实现了聊天系统的脏话,广告检测
  34. "Python instance" was shocked and realized the dirty words and advertisement detection of the chat system in Python
  35. Convolutional neural network processing sequence for Python deep learning
  36. Python data structure and algorithm (1) -- enum type enum
  37. 超全大厂算法岗百问百答(推荐系统/机器学习/深度学习/C++/Spark/python)
  38. 【Python进阶】你真的明白NumPy中的ndarray吗?
  39. All questions and answers for algorithm posts of super large factories (recommended system / machine learning / deep learning / C + + / spark / Python)
  40. [advanced Python] do you really understand ndarray in numpy?
  41. 【Python进阶】Python进阶专栏栏主自述:不忘初心,砥砺前行
  42. [advanced Python] Python advanced column main readme: never forget the original intention and forge ahead
  43. python垃圾回收和缓存管理
  44. java调用Python程序
  45. java调用Python程序
  46. Python常用函数有哪些?Python基础入门课程
  47. Python garbage collection and cache management
  48. Java calling Python program
  49. Java calling Python program
  50. What functions are commonly used in Python? Introduction to Python Basics
  51. Python basic knowledge
  52. Anaconda5.2 安装 Python 库(MySQLdb)的方法
  53. Python实现对脑电数据情绪分析
  54. Anaconda 5.2 method of installing Python Library (mysqldb)
  55. Python implements emotion analysis of EEG data
  56. Master some advanced usage of Python in 30 seconds, which makes others envy it
  57. python爬取百度图片并对图片做一系列处理
  58. Python crawls Baidu pictures and does a series of processing on them
  59. python链接mysql数据库
  60. Python link MySQL database