javascriptpythonjsonflaskplotly

Plotly Charts Not Displaying Correctly Despite Valid Data and Code


I'm facing a strange issue where none of my Plotly charts display correctly, even though the data is valid and the code runs without errors. This includes various chart types like line, bar, pie, and scatter charts.

Problem:

Context: I'm using Plotly with Flask in a web app. The charts are passed to the frontend using plotly.utils.PlotlyJSONEncoder and rendered using Plotly.newPlot() in JavaScript. Here’s an example of how I generate and pass a chart:

Python (Flask backend):

import json
import plotly.graph_objs as go
from flask import render_template

@app.route("/weather")
def weather():
    fig = go.Figure(data=go.Bar(x=["Mon", "Tue", "Wed"], y=[2, 5, 3]))
    graphJSON = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder)
    return render_template("weather.html", graphJSON=graphJSON)

HTML (Jinja + JavaScript frontend):

<div id="plot"></div>
<script>
    var graph = {{ graphJSON | safe }};
    Plotly.newPlot("plot", graph.data, graph.layout);
</script>

What I tried:

What I expected:

Charts should render based on the data e.g., bar charts with correct heights, pie charts with correct slices, and heatmaps with accurate density. Instead, the visuals don't align with the actual data, or appear empty or broken.

Expected Output (when using .show() in Python) (https://i.sstatic.net/gzRyqWIz.png)

Actual Output (on the webpage via Flask and Plotly.newPlot())(https://i.sstatic.net/KIf5eUGy.png)


Solution

  • Your issue happens because you're passing graph.data and graph.layout separately in js, but it's better to pass the entire fig.to_json() object directly to Plotly.newPlot(). This ensures the data structure matches what Plotly.js expects. also, make sure your Plotly Python and Plotly.js versions match cuz version mismatches can cause these kinds of bugs.

    paste this part of the code.

    Plotly.newPlot("plot", graph);