【python 視覺化】pyecharts + Django 使用指南
本指南按照 Django 官方教程,通過完成一個 Django 小專案來說明如何在 Django 中使用 pyecharts。如果對 Django 還不太熟悉的開發者,可仔細閱讀官方提供的最新文件。
Step 0: 使用新的 virtualenv 環境
建議開發者使用 1.11.4 版本的 Django
$ virtualenv --no-site-packages pyecharts-env
$ source pyecharts-env/bin/activate
$ pip install django==1.11.4
$ pip install pyecharts
Step 1: 新建一個 django 專案
$ django-admin startproject myechartsite
建立一個應用程式
$ python manage.py startapp myfirstvis
$ ls
db.sqlite3 manage.py myechartsite myfirstvis
在 myechartsite/settings.py 中註冊應用程式
# myechartsite/settings.py
...
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes' ,
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myfirstvis' # <---
]
...
我們先編輯 urls.py.這檔案在 Django 裡的功能是把前段的 HTTP 需求和後臺服務函式掛鉤。在 Step3,我們再引入後端服務函式
# myfirstvis/urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$' , views.index, name='index'),
]
在 myechartsite/urls.py 中新增 'myfirstvis.urls'
myechartsite/urls.py
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'myfirstvis/', include('myfirstvis.urls')) # <---
]
Step 2: 處理檢視功能部分
將下列程式碼儲存到 myfirstvis/views.py 中。
from __future__ import unicode_literals
import math
from django.http import HttpResponse
from django.template import loader
from pyecharts import Line3D
from pyecharts.constants import DEFAULT_HOST
def index(request):
template = loader.get_template('myfirstvis/pyecharts.html')
l3d = line3d()
context = dict(
myechart=l3d.render_embed(),
host=DEFAULT_HOST,
script_list=l3d.get_js_dependencies()
)
return HttpResponse(template.render(context, request))
def line3d():
_data = []
for t in range(0, 25000):
_t = t / 1000
x = (1 + 0.25 * math.cos(75 * _t)) * math.cos(_t)
y = (1 + 0.25 * math.cos(75 * _t)) * math.sin(_t)
z = _t + 2.0 * math.sin(75 * _t)
_data.append([x, y, z])
range_color = [
'#313695', '#4575b4', '#74add1', '#abd9e9', '#e0f3f8', '#ffffbf',
'#fee090', '#fdae61', '#f46d43', '#d73027', '#a50026']
line3d = Line3D("3D line plot demo", width=1200, height=600)
line3d.add("", _data, is_visualmap=True,
visual_range_color=range_color, visual_range=[0, 30],
is_grid3D_rotate=True, grid3D_rotate_speed=180)
return line3d
script_list 是 Page() 類渲染網頁所需要依賴的 echarts js 庫,依賴的庫的數量取決於所要渲染的圖形種類。
Step 3: 為專案提供自己的模板
前面的步驟是按照 tutorial part 1,接下來我們跳到 tutorial part 3
Linux/macos 系統
$ mkdir templates/myfirstvis -p
Windows 系統
在 myfirstvis 目錄下,新建 templates/myfirstvis 子目錄
myfirstvis 目錄
─ myfirstvis
├── admin.py
├── apps.py
├── init.py
├── migrations
│ ├── init.py
├── models.py
├── templates
│ └── myfirstvis
│ └── pyecharts.html
├── tests.py
├── urls.py
└── views.py
將下面 html 模板程式碼儲存為 pyecharts.html,請確保 pyecharts.html 檔案的絕對路徑為 /myfirstvis/templates/myfirstvis
<!-- myfirstvis/templates/pyecharts.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Proudly presented by PycCharts</title>
{% for jsfile_name in script_list %}
<script src="{{host}}/{{jsfile_name}}.js"></script>
{% endfor %}
</head>
<body>
{{myechart|safe}}
</body>
</html>
Step 4: 執行專案
$ cd myechartsite
$ python manage.py runserver
You have 13 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
August 08, 2017 - 05:48:38
Django version 1.11.4, using settings 'myechartsite.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.