'Plotly graph legend groups feature is different when using fig.show() and Flask

I am developing a Flask application and a graph I am plotting with Plotly needs groups in the legend. I followed this answer to achieve what I wanted. It works well when showing the graph with 'fig.show()' but when giving the graph with Flask, it doesn't display the legend correctly. Where could the issue come from ?

What Flask render

What 'fig.show()' display, that I want

Flask code:

import json
import pandas as pd
import plotly.utils
from flask import Flask, render_template
import plotly.express as px
import numpy as np

app = Flask(__name__)

@app.route('/')
def hello_world():
    df = pd.DataFrame.from_dict({'x': {0: 'x1', 1: 'x1', 2: 'x2', 3: 'x2', 4: 'x2'},
                                 'z': {0: 'z1', 1: 'z2', 2: 'z1', 3: 'z2', 4: 'z3'},
                                 'n': {0: 'n1', 1: 'n2', 2: 'n1', 3: 'n1', 4: 'n2'},
                                 'y': {0: 10, 1: 12, 2: 13, 3: 9, 4: 14}})
    df.x = df.x.astype('category')
    df.z = df.z.astype('category')
    df.n = df.n.astype('category')
    fig = px.scatter(df, y="y", x="x", color="n", symbol="z", category_orders={'n': np.sort(df['n'].unique())},
                     title='test_graph', width=800, height=600)
    legend_traces = [px.scatter(df, x="x", y=np.full(len(df), float('NaN')), **param["px"])
                         .update_traces(**param["lg"], legendgroup=str(param["px"]))
                     for param in [
                         {"px": {"color": "n"}, "lg": {"legendgrouptitle_text": "N"}},
                         {"px": {"symbol": "z"}, "lg": {"legendgrouptitle_text": "Z"}}
                     ]
                     ]
    for t in legend_traces:
        fig.add_traces(t.data)
    graphJSON = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder)
    fig.show()

    return render_template('main.html', graphJSON=graphJSON)


if __name__ == '__main__':
    app.run()

And HTML code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>test_flask</title>
</head>
<body>
<div id="chart" class="chart"></div>
</body>
<script src='https://cdn.plot.ly/plotly-latest.min.js'></script>
<script type='text/javascript'>
  var graphs = {{graphJSON | safe}};
  Plotly.plot('chart',graphs,{});
</script></html>
</html>


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source