Search code examples
javascriptpythonpython-3.xflaskplotly

How to pass a list of plotly graphs to javascript and plot them dynamically


I have a list of plotly graphs in python. I would like to pass them to JavaScript and plot them dynamically because the list is always dynamic based on an excel file. This is the way I currently do it below:

@app.route("/dashboard")
@login_required
def dashboard():
    graphs = [...] # list of plotly graphs
    ids = [...] # list of ids for the graphs
    plot1= graphs[0]
    plot2 = graphs[1]
    plot3 = graphs[2]
    plot4 = graphs[3]

    return render_template(
            "some_template.html",
            plot1 = plot1,
            plot2 = plot2,
            plot3 = plot3,
        )

Then in JS I do the following:

<script type="text/javascript">

  var graph1 = {{plot1 | safe}};
  Plotly.plot("plot1",graph1, {});

  var graph2 = {{plot2| safe}};
  Plotly.plot("plot2",graph2, {});

  var graph3= {{plot3| safe}};
  Plotly.plot("plot3",graph3, {});

</script>

This works well, however, the problem is that since the list is always dynamic I can run into problems. the length of ids is always the same length of graphs and is in order.

This is the way I tried to approach it:

 @app.route("/dashboard")
    @login_required
    def dashboard():
        graphs = [...] # list of plotly graphs
        ids = [...] # list of ids for the graphs
    
        return render_template(
                "some_template.html",
                graphs=graphs,
                ids = json.dumps(ids)
            )

Then in JS I do the following:

var graphs = {{graphs | safe}};
var ids = {{ids | safe}};


  for (var i = 0; i < graphs.length; i++){
    var current_graph = graphs[i];
    current_graph.config={displayModeBar: false}
    Plotly.plot(String(ids[i]), current_graph, {});
  }

This approach just shows empty graphs. What am I doing wrong? please advise?


Solution

  • Try to do everything through jinja:

    @app.route("/dashboard")
    @login_required
    def dashboard():
        graphs = [{"graph_id": your_graph}, ...] # list of plotly dict
        return render_template(
                "some_template.html",
                graphs=graphs,
            )
    
    <script type="text/javascript">
    {% for dict_item in graphs %}
        Plotly.plot({{dict_item.id}}, {{dict_item.graph}}, {});
    {% endfor %}
    </script>
    

    If you are not sure what the grapg variable contains, print it on the console and verify that it is correctly valued:

    <script type="text/javascript">
    {% for dict_item in graphs %}
        console.log({{dict_item.graph}});
        Plotly.plot({{dict_item.id}}, {{dict_item.graph}}, {});
    {% endfor %}
    </script>