实现方案
通过前端网元的定时刷新,实现前后台数据的实时同步。前端画图使用echarts.js插件,插件详细使用方法请参考官方网站。
后端python代码
使用flask框架,需提前进行安装(pip install flask)。
from flask import Flask, render_template, jsonify
import numpy as np
import pandas as pd
app = Flask(__name__)
@app.route('/')
def home():
return render_template('index.html')
@app.route('/data')
def data():
# 这里你可以生成要动态更新的数据
chart_data = {
'x': ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'],
'y1':[11111, 11111, 234, 11111, 9987, 11111],
'y2': [2223, 2323, np.random.randint(100,1000), 688, np.random.randint(100,1000), 1330]
}
return jsonify(chart_data)
@app.route('/plotdata')
def plotdata():
# 这里你可以生成或获取你的数据,从CSV或数据库获取动态数据
df=pd.read_csv('报表1111.csv',encoding='gbk')
df2=df[['日期','value1','value2']]
df2=df2.reset_index(drop=True)
df2['日期']=pd.to_datetime(df2['日期'])
df2['日期']=df2['日期'].dt.strftime('%Y-%m-%d')
df3=df2.groupby('日期').mean()
df3=df3.reset_index(drop=False)
df3=df3.round(2)
chart_data={
'x': df3['日期'].tolist(),
'y1': df3['value1'].tolist(),
'y2': df3['value2'].tolist()
}
return jsonify(chart_data)
@app.route('/piedata')
def piedata():
# 这里你可以生成或获取你的数据
chart_data = {
'x': [
{ 'value': np.random.rand(), 'name': 'Search Engine' },
{ 'value': np.random.rand(), 'name': 'Direct' },
{ 'value': np.random.rand(), 'name': 'Email' },
{ 'value': np.random.rand(), 'name': 'Union Ads' },
{ 'value': np.random.rand(), 'name': 'Video Ads' }
]
}
return jsonify(chart_data)
if __name__ == '__main__':
app.run(debug=True)
前端HTML
使用echarts.min.js实现动态折线图绘制,使用远端echarts.js插件,适合公网用户。【内网用户需提前下载echarts.min.js插件(下载地址https://echarts.apache.org/zh/download.html),放入static/js目录下,并修改HTML代码中的<script src=‘*’>部分】,HTML模板(文件名称index.html)需存放在templates目录下。
前端代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ECharts Examples</title>
<script src="https://cdn.staticfile.org/echarts/4.3.0/echarts.min.js">
</script>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
}
#chart {
width: 100%;
height: 600px;
}
#chart2 {
width: 100%;
height: 600px;
}
#chart3 {
width: 100%;
height: 600px;
}
#chart4 {
width: 100%;
height: 600px;
}
</style>
</head>
<body>
<h1 style="text-align: center;">ECharts 示例</h1>
<div id="chart"></div>
<div id="chart2"></div>
<div id="chart3"></div>
<div id="chart4"></div>
<script>
// 定义一个函数,用于自动刷新页面
function autoRefresh() {
setInterval(function() {
location.reload();
}, 15000);
}
// 页面加载完毕后调用 autoRefresh 函数
window.onload = autoRefresh;
// 初始化 ECharts 实例
var myChart1 = echarts.init(document.getElementById('chart'));
var myChart2 = echarts.init(document.getElementById('chart2'));
var myChart3 = echarts.init(document.getElementById('chart3'));
var myChart4 = echarts.init(document.getElementById('chart4'));
// 请求数据
fetch('/data')
.then(response => response.json())
.then(data => {
// 设置图表1配置项和数据,2个类别的柱状图
var option1 = {
title: {
text: 'test表111',
left: 'center'
},
tooltip: {},
legend: {
orient: 'vertical',
left: 'right'
},
xAxis: {
data: data.x
},
yAxis: {},
series: [{
name: '销量',
type: 'bar',
barGap: '0%',
data: data.y1
},
{
name: '列表2',
type: 'bar',
data: data.y2
}]
};
// 使用配置项和数据显示图表
myChart1.setOption(option1);
});
fetch('/data')
.then(response => response.json())
.then(data => {
// 设置图表2柱状图的参数,一个类别的柱状图
var option2 = {
title: {
text: 'test表222'
},
tooltip: {},
xAxis: {
data: data.x
},
yAxis: {},
series: [{
name: '销量',
type: 'bar',
barGap: '0%',
data: data.y1
}]
};
// 使用配置项和数据显示图表
myChart2.setOption(option2);
});
fetch('/plotdata')
.then(response => response.json())
.then(data => {
// 设置 图表3 折线图的 配置项和数据
var option3 = {
title: {
text: '折线图111'
},
<!-- tooltip,鼠标悬浮显示数据-->
tooltip: {},
xAxis: {
type: 'category',
data: data.x
},
yAxis: {
type: 'value'
},
<!-- // legend用于图表类别名称的设置-->
<!-- legend: {-->
<!-- orient: 'vertical',-->
<!-- left: 'left'-->
<!-- data, 图例类别名,需要与series中的name对应-->
<!-- data:[data.ylabel1,data.ylabel2]-->
<!-- },-->
<!-- // 折线上显示数据-->
<!-- // label: {-->
<!-- // show: true-->
<!-- // },-->
series: [
{
// name: data.ylabel2
data: data.y2,
type: 'line'
},
{
// name:data.ylabel1
data: data.y1,
type: 'line'
}
]
};
// 使用配置项和数据显示图表
myChart3.setOption(option3);
});
fetch('/piedata')
.then(response => response.json())
.then(data => {
// 设置 图表4 饼图的 配置项和数据
var option4 = {
// 图表标题设置
title: {
text: '饼子图4',
subtext: 'Data',
left: 'center'
},
tooltip: {
trigger: 'item'
},
legend: {
orient: 'vertical',
left: 'right'
},
series: [
{
name: 'Access From',
type: 'pie',
radius: '50%',
data: data.x,
emphasis: {
itemStyle: {
shadowBlur: 10,
shadowOffsetX: 0,
shadowColor: 'rgba(0, 0, 0, 0.5)'
}
}
}
]
};
// 使用配置项和数据显示图表
myChart4.setOption(option4);
});
</script>
</body>
</html>
效果图: