一瑟捣、安裝pyecharts
??Echarts 是一個由百度開源的數(shù)據(jù)可視化馋艺,憑借著良好的交互性,精巧的圖表設(shè)計迈套,得到了眾多開發(fā)者的認(rèn)可丈钙。而 Python 是一門富有表達(dá)力的語言,很適合用于數(shù)據(jù)處理交汤。當(dāng)數(shù)據(jù)分析遇上數(shù)據(jù)可視化時,pyecharts 誕生了。
特性:
簡潔的 API 設(shè)計芙扎,使用如絲滑般流暢星岗,支持鏈?zhǔn)秸{(diào)用
囊括了 30+ 種常見圖表,應(yīng)有盡有
支持主流 Notebook 環(huán)境戒洼,Jupyter Notebook 和 JupyterLab
可輕松集成至 Flask俏橘,Sanic,Django 等主流 Web 框架
高度靈活的配置項圈浇,可輕松搭配出精美的圖表
詳細(xì)的文檔和示例寥掐,幫助開發(fā)者更快的上手項目
多達(dá) 400+ 地圖文件,并且支持原生百度地圖磷蜀,為地理數(shù)據(jù)可視化提供強有力的支持
V1:僅支持 Python3.6+
文檔示例:http://pyecharts.herokuapp.com/
官網(wǎng):https://github.com/pyecharts/pyecharts
二召耘、安裝PyEcharts
pip install pyecharts -U
安裝組件:
二、顯示PyCharts
- Web直接顯示
from flask import Flask
from pyecharts.charts import Bar
from pyecharts import options as opts
from flask import Markup
app = Flask(__name__)
app.config["DEBUG"] = True
# 定義條圖
def bar_base() -> Bar:
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="我是副標(biāo)題"))
)
return c
# 路由
@app.route("/")
def index():
c = bar_base()
return Markup(c.render_embed())
if __name__ == '__main__':
app.run() # 設(shè)置debug=True是為了讓代碼修改實時生效褐隆,而不用每次重啟加載
- Flask 前后端分離
在 templates 文件夾中新建一個 index.html 的文件污它,其中主要用到了 jquery 和 pyecharts 管理的 echarts.min.js 依賴。
1)前端頁面
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>動態(tài)更新數(shù)據(jù)</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:1000px; height:600px;"></div>
<script>
(function() {
var result_json = '{{ result_json|tojson }}';
// var result = JSON.parse(result_json);
var chart = echarts.init(document.getElementById('bar'), 'gray', {renderer: 'canvas'});
// ajax請求
$.ajax({
type: "GET",
url: "http://127.0.0.1:5000/barChart",
dataType: 'json',
data: {result: result_json},
success: function (result) {
chart.setOption(result);
}
});
})();
</script>
</body>
</html>
2)后端代碼
from flask import Flask
from flask import render_template
# http請求庫
from flask import request
# pyecharts 庫
from pyecharts import options as opts
from pyecharts.charts import Bar
app = Flask(__name__)
app.config["DEBUG"] = True
# 根路徑庶弃,渲染模板index.html
@app.route("/")
def index():
data = request.args.to_dict()
print(data)
return render_template("index.html", result_json=data)
# 定義標(biāo)題參數(shù)繪制條圖的函數(shù)
def bar_base(name,subtitle) -> Bar:
c = (
Bar()
.add_xaxis(["襯衫", "羊毛衫", "雪紡衫", "褲子", "高跟鞋", "襪子"])
.add_yaxis("商家A", [5, 20, 36, 10, 75, 90])
.add_yaxis("商家B", [15, 25, 16, 55, 48, 8])
# 顯示動態(tài)標(biāo)題
.set_global_opts(title_opts=opts.TitleOpts(title=name, subtitle=subtitle))
)
return c
@app.route("/barChart")
def get_bar_chart():
# 接受請求參數(shù)
args = request.args.to_dict()
result = eval(args.get("result"))
name = result.get("name")
subtitle = result.get("subtitle")
c = bar_base(name, subtitle)
return c.dump_options_with_quotes()
if __name__ == '__main__':
app.run() # 設(shè)置debug=True是為了讓代碼修改實時生效衫贬,而不用每次重啟加載
- 瀏覽測試
請求地址:http://127.0.0.1:5000/?name=test&subtitle=test
必須添加請求參數(shù)。
- 動態(tài)數(shù)據(jù)顯示
1)前端頁面
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>動態(tài)更新數(shù)據(jù)</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:1000px; height:600px;"></div>
<script>
var chart = echarts.init(document.getElementById('bar'), 'white', {renderer: 'canvas'});
// 每2秒更新一次
$(
function () {
fetchData(chart);
setInterval(fetchData, 2000);
}
);
// 定義函數(shù)歇攻,從后臺獲取數(shù)據(jù)
function fetchData() {
$.ajax({
type: "GET",
url: "http://127.0.0.1:5000/barChart",
dataType: 'json',
success: function (result) {
chart.setOption(result);
}
});
}
</script>
</body>
</html>
2)后端代碼
from flask import Flask
from flask import render_template
# 隨機(jī)函數(shù)
import random
# pyecharts 庫
from pyecharts import options as opts
from pyecharts.charts import Bar
app = Flask(__name__)
app.config["DEBUG"] = True
# 根路徑固惯,渲染模板index.html
@app.route("/")
def index():
return render_template("index.html")
# 隨機(jī)數(shù)據(jù)條圖
def bar_base() -> Bar:
c = (
Bar()
.add_xaxis(["襯衫", "羊毛衫", "雪紡衫", "褲子", "高跟鞋", "襪子"])
.add_yaxis("商家A", [random.randint(10, 100) for _ in range(6)])
.add_yaxis("商家B", [random.randint(10, 100) for _ in range(6)])
.set_global_opts(title_opts=opts.TitleOpts(title="", subtitle=""))
)
return c
@app.route("/barChart")
def get_bar_chart():
c = bar_base()
return c.dump_options_with_quotes()
if __name__ == '__main__':
app.run() # 設(shè)置debug=True是為了讓代碼修改實時生效,而不用每次重啟加載
3)瀏覽顯示
- 使用變量獲取數(shù)據(jù)
1)html文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>圖表示例</title>
<style>
.charts {
/*background-color: red;*/
height: 500px;
width: 600px;
}
</style>
<script src="../static/js/echarts.min.js"></script>
</head>
<body>
<div id="charts" class="charts"></div>
<div id="data" style="display: none">{{list}}</div>
<script>
var list = document.getElementById("data");
var d = document.getElementById("charts");
// 初始化圖表
var chart = echarts.init(d);
option = {
title: {
text: '第一個小例子'
},
tooltip: {},
legend: {
data: ['銷量']
},
xAxis: {
// 讀取后臺數(shù)據(jù)轉(zhuǎn)為json
data: JSON.parse(list.innerText)
},
yAxis: {},
series: [{
name: '銷量',
type: 'bar',
data: [35, 20, 56, 100, 80, 64]
}]
};
chart.setOption(option);
</script>
</body>
</html>
- python數(shù)據(jù)
from flask import Flask, url_for, request, jsonify, render_template
# json 解析
import json
app = Flask(__name__)
@app.route("/charts")
def getCharts():
data = ["襯衫", "羊毛衫", "雪紡衫", "褲子", "高跟鞋", "襪子"]
# 必須使用json.dumps進(jìn)行轉(zhuǎn)換 json.dumps是將一個Python數(shù)據(jù)類型列表進(jìn)行json格式的編碼解析
# 否則雙引號會轉(zhuǎn)為單引號缴守,導(dǎo)致前臺無法解析此內(nèi)容
return render_template("charts.html", list=json.dumps(data))
if __name__ == "__main__":
# 啟動flask
app.run(port=9999, debug=True)
-
瀏覽訪問