In this tutorial you will learn how to use pyecharts for visualization in the Flask of the Web Framework. In this tutorial you will learn how to display visualization data dynamically in the Flask of the Web framework.

Flask template rendering

1. Create a new project flask-Echarts

Select New Project in the editor, then Flask, and Pycharm will help us create the startup script and template folder

2. Copy the Pyecharts template

Link to the following template ├── jupyter_lab.html ├── jupyter_note.html ├── macro ├─ nteract.html ├─ simple_chart.html ├─ └ _page.html ├ ─ page.html github.com/pyecharts/p…

3. Render charts

The main goal is to return the chart data generated by PyEcharts in the view function, so we modify the code directly in app.py as follows:

from flask import Flask
from jinja2 import Markup


from pyecharts import options as opts
from pyecharts.charts import Bar

app = Flask(__name__, static_folder="templates")


def bar_base(a) -> Bar:
    c = (
        Bar()
            .add_xaxis(["Shirt"."Cardigan"."Chiffon shirt."."Pants"."High heels"."Socks"])
            .add_yaxis("Merchants A"[5.20.36.10.75.90])
            .add_yaxis(Merchants "B"[15.25.16.55.48.8])
            .set_global_opts(title_opts=opts.TitleOpts(title="Bar- Basic Example", subtitle="I'm the subtitle.")))return c


@app.route("/")
def index(a):
    c = bar_base()
    return Markup(c.render_embed())


if __name__ == "__main__":
    app.run()
Copy the code

Run directly, enter the address in the browser, directly display the data

The front and rear ends of the Flask are separated

The above is a static data display method, pyecharts and Flask combined with the most important is to achieve a dynamic update data, incremental update data and other functions! Build a new index.html file in the Templates folder that uses jquery and the Echarts.min.js dependencies managed by Pyecharts.

index.html


      
<html>
<head>
    <meta charset="UTF-8">
    <title>Dynamically updating data</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({
                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>
Copy the code

For those of you who are familiar with HTML, this code mainly sends requests to the address “127.0.0.1:5000/barChart”, so we need to add a routing function for that address in app.py to implement dynamic data updates. Part of the code is as follows:

@app.route("/")
def index(a):
    data = request.args.to_dict()
    return render_template("index.html", result_json=data)

@app.route("/barChart")
def get_bar_chart(a):
    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()
Copy the code

The index view function receives arguments from the browser and passes them to index.html. This is only a simple example, so no parameter verification is done. The other view function mainly takes parameters and passes them to the chart generating function bar_base() to dynamically display the chart data based on the parameters passed from the URL address. The results are as follows:

This is a simple demonstration, so only the chart title is used as a dynamic parameter. This scenario applies to the first request to get the data we want, and then to present it. Like I wrote before NBA player data visualization mp.weixin.qq.com/s/WWCNf46Ch…

This is the method, different players display corresponding player data!

Update the chart regularly and in full

In this scenario, the front end actively refreshes data to the back end. The core of the periodic refresh is the setInterval method of HTML. So the index.html code looks like this:


      
<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>
        var chart = echarts.init(document.getElementById('bar'), 'white', {renderer: 'canvas'});

        $(
            function () {
                fetchData(chart);
                setInterval(fetchData, 2000); });function fetchData() {
            $.ajax({
                type: "GET".url: "http://127.0.0.1:5000/barChart".dataType: 'json'.success: function (result) { chart.setOption(result); }}); }</script>
</body>
</html>
Copy the code

Accordingly, bar_base() in app.py is modified accordingly, so as to realize periodic full update chart

def bar_base(a) -> Bar:
    c = (
        Bar()
            .add_xaxis(["Shirt"."Cardigan"."Chiffon shirt."."Pants"."High heels"."Socks"])
            .add_yaxis("Merchants A", [random.randint(10.100) for _ in range(6)])
            .add_yaxis(Merchants "B", [random.randint(10.100) for _ in range(6)])
            .set_global_opts(title_opts=opts.TitleOpts(title="", subtitle="")))return c

@app.route("/")
def index(a):
    return render_template("index.html")

@app.route("/barChart")
def get_bar_chart(a):
    c = bar_base()
    return c.dump_options_with_quotes()
Copy the code

After running it, open it in a browser and the result is as follows:

Looking at this GIF, is there a kind of… If I were DJ DJ you’re so beautiful…

Update the chart periodically incrementally

Also make changes to index.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>
        var chart = echarts.init(document.getElementById('bar'), 'white', {renderer: 'canvas'});
        var old_data = [];
        $(
            function () {
                fetchData(chart);
                setInterval(getDynamicData, 2000); });function fetchData() {
            $.ajax({
                type: "GET".url: "http://127.0.0.1:5000/lineChart".dataType: "json".success: function (result) {
                    chart.setOption(result);
                    old_data = chart.getOption().series[0].data; }}); }function getDynamicData() {
            $.ajax({
                type: "GET".url: "http://127.0.0.1:5000/lineDynamicData".dataType: "json".success: function (result) {
                    old_data.push([result.name, result.value]);
                    chart.setOption({
                        series: [{data: old_data}] }); }}); }</script>
</body>
</html>
Copy the code

Incremental updates, and the back-end code needs to change accordingly

from pyecharts.charts import Line

def line_base(a) -> Line:
    line = (
        Line()
        .add_xaxis(["{}".format(i) for i in range(10)])
        .add_yaxis(
            series_name="",
            y_axis=[randrange(50.80) for _ in range(10)],
            is_smooth=True,
            label_opts=opts.LabelOpts(is_show=False),
        )
        .set_global_opts(
            title_opts=opts.TitleOpts(title="Dynamic data"),
            xaxis_opts=opts.AxisOpts(type_="value"),
            yaxis_opts=opts.AxisOpts(type_="value")))return line

@app.route("/")
def index(a):
    return render_template("index.html")

@app.route("/lineChart")
def get_line_chart(a):
    c = line_base()
    return c.dump_options_with_quotes()

idx = 9

@app.route("/lineDynamicData")
def update_line_data(a):
    global idx
    idx = idx + 1
    return jsonify({"name": idx, "value": randrange(50.80)})
Copy the code

Let’s go. Let’s see what happens

Thanks for reading and following!