資料分析(四) pyecharts和Tornado
阿新 • • 發佈:2021-10-18
在Tornado框架中使用pyecharts
官方示例:https://pyecharts.org/#/zh-cn/web_tornado
首先新建專案呵呵HTML檔案server.py、index.html
index.html
<!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:1000px; height:600px;"></div> <script> $( function () { var chart = echarts.init(document.getElementById('bar'), 'white', {renderer: 'canvas'}); $.ajax({ type: "GET", url: "http://127.0.0.1:8889/getBarChart", dataType: 'json', success: function (result) { chart.setOption(result); } }); } ) </script> </body> </html>
server.py
注: 目前由於 json 資料型別的問題,無法將 pyecharts 中的 JSCode 型別的資料轉換成 json 資料格式返回到前端頁面中使用。因此在使用前後端分離的情況下儘量避免使用 JSCode 進行畫圖。
此程式碼示例中使用的是柱狀圖
import tornado.web import tornado.ioloop import tornado.httpserver from pyecharts.charts import Bar from pyecharts import options as opts def bar_base() -> str: 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="我是副標題")) ) return c.dump_options()def set_default_header(self): # 後面的*可以換成ip地址,意為允許訪問的地址 self.set_header("Access-Control-Allow-Origin", "*") self.set_header("Access-Control-Allow-Headers", "x-requested-with") self.set_header("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE") self.set_header("Content-Type", "application/json; charset=UTF-8") class BarChart(tornado.web.RequestHandler): def data_received(self, chunk): pass def get(self): set_default_header(self) chart_result = bar_base() # 返回結果 self.write(chart_result) self.finish() class PageHandler(tornado.web.RequestHandler): def data_received(self, chunk): pass def get(self): self.render("index.html") def make_app(): return tornado.web.Application([ (r"/", PageHandler), (r"/getBarChart", BarChart), ]) if __name__ == "__main__": port = 8889 app = make_app() sockets = tornado.netutil.bind_sockets(port) http_server = tornado.httpserver.HTTPServer(app) http_server.add_sockets(sockets) print("Server Start Running!\nHost: {} Port: {}".format("127.0.0.1", port)) tornado.ioloop.IOLoop.instance().start()