简体   繁体   中英

Rendering mpld3 JSON chart in React

Good day.

I just recently came across mpld3 and I am trying to see if it will be the solution to my issue.

I want to create Matplotlib charts in Python, save them as JSON objects to a database, and then render them in my React webpage.

So far I have created a plot in Python, using Matplotlib and converted it to a JSON object in a dictionary:

fig = plt.gcf()
mpld3.display(fig)
fig_to_dict = mpld3.fig_to_dict(fig)

Now I can save the dictionary to a file.

My question is: Can I then render this JSON chart in my React project? And if so, how do I do that?

Another thing is - I cannot use D3 in the front-end, I need to do all my "chart making" in the back-end.

Thank you for any and all assistance!

This is not a perfect answer, but I seemed to be solving a similar problem and I appear to have got it working so am sharing my code as is. Hopefully it will prove useful to someone.

This is my react component ('matPlotLibFig.js') that renders a simple figure

import React from 'react'
import mpld3_load_lib from "./mpld3_load_lib";
import mpld3 from 'mpld3'
import _json from "./plot_b.json"
const MatPlotLibFig = () => {
  const fig_name = "fig_el427345810798888193429725"
  return <div>
    <script>
      mpld3_load_lib("https://d3js.org/d3.v5.js", function () {
        mpld3_load_lib("https://mpld3.github.io/js/mpld3.v0.5.8.js", function () {
          mpld3.remove_figure(fig_name)
          mpld3.draw_figure(fig_name, _json);
        })
      });
    </script>
    <div id={fig_name}></div>
  </div>
}
export default MatPlotLibFig

plot_b.json:

{
  "width": 640.0,
  "height": 480.0,
  "axes": [
    {
      "bbox": [0.125, 0.11, 0.775, 0.77],
      "xlim": [-0.5, 10],
      "ylim": [0, 10],
      "xdomain": [-0.2, 10],
      "ydomain": [0.0, 10],
      "xscale": "linear",
      "yscale": "linear",
      "axes": [
        {
          "position": "bottom",
          "nticks": 11,
          "tickvalues": null,
          "tickformat_formatter": "",
          "tickformat": null,
          "scale": "linear",
          "fontsize": 10.0,
          "grid": {
            "gridOn": false
          },
          "visible": true
        },
        {
          "position": "left",
          "nticks": 11,
          "tickvalues": null,
          "tickformat_formatter": "",
          "tickformat": null,
          "scale": "linear",
          "fontsize": 10.0,
          "grid": {
            "gridOn": false
          },
          "visible": true
        }
      ],
      "axesbg": "#FFFFFF",
      "axesbgalpha": null,
      "zoomable": true,
      "id": "el91906139874005984112",
      "lines": [
        {
          "data": "data01",
          "xindex": 0,
          "yindex": 1,
          "coordinates": "data",
          "id": "el91906139873968544448",
          "color": "#000000",
          "linewidth": 1.5,
          "dasharray": "none",
          "alpha": 1,
          "zorder": 2,
          "drawstyle": "default"
        }
      ],
      "paths": [],
      "markers": [
        {
          "data": "data01",
          "xindex": 0,
          "yindex": 1,
          "coordinates": "data",
          "id": "el91906139873968544448pts",
          "facecolor": "#000000",
          "edgecolor": "#FFFFFF",
          "edgewidth": 5,
          "alpha": 1,
          "zorder": 2,
          "markerpath": [
            [
              [
                -10.0,
                10.0
              ],
              [
                10.0,
                10.0
              ],
              [
                10.0,
                -10.0
              ],
              [
                -10.0,
                -10.0
              ]
            ],
            [
              "M",
              "L",
              "L",
              "L",
              "Z"
            ]
          ]
        }
      ],
      "texts": [],
      "collections": [],
      "images": [],
      "sharex": [],
      "sharey": []
    }
  ],
  "data": {
    "data01": [
      [
        0.0,
        6.0
      ],
      [
        1.0,
        2.0
      ],
      [
        2.0,
        8.0
      ],
      [
        3.0,
        3.0
      ],
      [
        4.0,
        0.0
      ],
      [
        5.0,
        7.0
      ]
    ]
  },
  "id": "el91906139874196422128",
  "plugins": [
    {
      "type": "reset"
    },
    {
      "type": "zoom",
      "button": true,
      "enabled": false
    },
    {
      "type": "boxzoom",
      "button": true,
      "enabled": false
    }
  ]
}

mpld3_load_lib.js:

const mpld3_load_lib = (url, callback) => {
  var s = document.createElement('script');
  s.src = url;
  s.async = true;
  s.onreadystatechange = s.onload = callback;
  s.onerror = function () { console.warn("failed to load library " + url); };
  document.getElementsByTagName("head")[0].appendChild(s);
}
export default mpld3_load_lib

Which renders a dynamic plot that looks like简单的 matplotlib 图

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM