2

I want to create a chart on the backend and send it to the frontend to display it.

My endpoint /chart/ return plot this way:

from dataclasses import dataclass
import plotly.graph_objects as go
import plotly.io as pio


@dataclass
class DataChart:
    category: list[str]
    points: list[int]


class GenerateChart:
    def __init__(self, data: DataChart):
        assert isinstance(data, DataChart)
        self.category = data.category
        self.points = data.points

    def generate_chart(self):
        fig = go.Figure()

        fig.add_trace(
            go.Scatterpolar(
                r=self.points,
                theta=self.category,
                fill="toself",
                name="A",
            )
        )
        fig.update_layout(
            polar={"radialaxis": {"visible": True, "range": [0, 10]}}, showlegend=False
        )
        html_str = pio.to_html(fig, include_plotlyjs="cdn", full_html=False)
        return html_str

and frontend:

  const generateChart = async (queue_smooth_data: {}) => {
      const response = await fetch("http://127.0.0.1:8000/chart/", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(queue_smooth_data),
      });
      response.text().then((text) => {
        setChartHTML(text);
      });

  if (currentQuestionIndex > dataQuiz.length) {
    return (
      <div>
        <div dangerouslySetInnerHTML={{ __html: chartHTML }}></div>
      </div>
    );
  }

but it returns in html this:

"
\n
"

Does anyone know where I made a mistake? My raw html data looks like this:

"<div> <div id=\"1d254924-7635-493b-87bb-e44ced485435\" class=\"plotly-graph-div\" style=\"height:100%; width:100%;\"></div> <script type=\"text/javascript\"> window.PLOTLYENV=window.PLOTLYENV || {}; if (document.getElementById ...

Additional question - is this a good way to upload charts? From what I've figured out usually you save the chart to a file and read it from there, but I want to just display the chart without unnecessarily saving it.

I tried different ways to send data - setting include_plotlyjs="cdn", True, False, also imported into HTML plotly:

<script
      src="https://cdn.plot.ly/plotly-2.20.0.min.js"
      charset="utf-8"
></script>

also installing plotlyjs npm

TenSzalik
  • 41
  • 4
  • 1
    You might find [this answer](https://stackoverflow.com/a/71213792/17865804) and [this answer](https://stackoverflow.com/a/73754985/17865804) helpful – Chris May 11 '23 at 15:48
  • I'm not sure why your plot is not rendering, but I wanna ask, if you're building a react frontend, why not use the [plotly react library](https://plotly.com/javascript/react/), and just expose the data you're plotting through a JSON endpoint? – M.O. May 11 '23 at 18:48
  • @M.O. In this project I am just more interested in learning the backend – TenSzalik May 12 '23 at 00:54

0 Answers0