知乎回答:Python 数据处理 + ECharts 本地访问(直接双击 html 页)

需求
- 图表需要不时更换数据,原始数据是 *.json
- 因为 jQuery 不支持 file 协议,但是又不想用 Web 中间件
- 提问者用 Python 做数据处理,所以可以使用 Python 的能力
实现方法
- 用 Python 读取 json,将其处理后(如果需要),转存成一个 *.js 文件
- 由这个 js 文件完成数据变量的定义(var data = ... )
- html 中引入这个 js 文件(<head>script src="data.js"></script></head>),渲染图表
示意代码
json 数据: data.json
{
"data": [
"value": 335,
"name": "直接访问"
"value": 310,
"name": "邮件营销"
"value": 274,
"name": "联盟广告"
"value": 235,
"name": "视频广告"
"value": 400,
"name": "搜索引擎"
}
Python 转存 js 文件(数据处理过程略~ 也可能是 pandas 读取 excel 处理后转存)
# -*- coding: utf-8 -*-
Created on Mon Jun 1 12:48:50 2020
@author: Administrator
import json
import codecs
filePath = "data.json"
data = json.load(codecs.open(filePath, "r", "utf-8-sig"))
except UnicodeDecodeError:
data = json.load(open(filePath))
jsStr = "// 数据变量\nvar data = " + str(data["data"]) + ";"
with codecs.open("data.js", "w", "utf-8") as f:
f.write(jsStr)
html 文件
这里参照了 ECharts 的官方示例 https://gallery.echartsjs.com/editor.html?c=pie-custom
<!DOCTYPE html>
<meta charset="utf-8">
<title>ECharts</title>
<!-- 引入 echarts.js -->
<script src="echarts.min.js"></script>
<!-- 引入 Python 生成的 js 文件 -->
<script src="data.js"></script>
</head>
<!-- 为ECharts准备一个具备大小(宽高)的Dom -->
<div id="main" style="width: 600px;height:400px;"></div>
<script type="text/javascript">
// 基于准备好的dom,初始化echarts实例
var myChart = echarts.init(document.getElementById('main'));
// 排序数据
data.sort(function (a, b) { return a.value - b.value });
// 指定图表的配置项和数据
var option = {
backgroundColor: '#2c343c',
title: {
text: 'Customized Pie',
left: 'center',
top: 20,
textStyle: {
color: '#ccc'
tooltip: {
trigger: 'item',
formatter: "{a} <br/>{b} : {c} ({d}%)"
visualMap: {
show: false,
min: 80,
max: 600,
inRange: {
colorLightness: [0, 1]
series: [
name: '访问来源',
type: 'pie',
radius: '55%',
center: ['50%', '50%'],
data: data,
roseType: 'angle',
label: {
normal: {
textStyle: {
color: 'rgba(255, 255, 255, 0.3)'
labelLine: {
normal: {
lineStyle: {
color: 'rgba(255, 255, 255, 0.3)'
smooth: 0.2,
length: 10,
length2: 20
itemStyle: {
normal: {
color: '#c23531',
shadowBlur: 200,
shadowColor: 'rgba(0, 0, 0, 0.5)'