Insert Python's mpld3 images to HTML without saving them

111 views Asked by At

I have a Python script, which does some computations and makes a figure. Then, I am using mpld3 to generate an HTML version of this figure and save it (e.g., figure.html). The Python computations are launched via the AJAX request to the HTTP server. In my JS file, I use the jQuery.load() method to insert the plot into HTML:

$("#includedContent").load('/figure.html'); 

In this way, everything seems to work fine. The question is can I do the same thing without saving the figures? I tried to return a figure as a response, here is my modified AJAX request:

$.ajax({
    type: "POST",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    url: "/main.py",
    data: JSON.stringify({ 'sim_dur': input }),
    success: function (response) {
        figure = response.figure;
        var child = document.createElement('div');
        child.innerHTML = figure;
        child = child.firstChild;
        document.getElementById('includedContent').appendChild(child);

    }
});

If I assign an HTML-like string to child.innerHTML, the code works correctly. But when I try to assign it a figure (which has a string type as well), it is not showing on the HTML page. I'm new to JS, so I apologize if it is something basic. I did some research and it seems that people usually save the results in other answers, so maybe it is a common way to do it and what I am trying to do is not right.

1

There are 1 answers

0
Cobry On

In my experience, mlpd3 will only work when the client (browser) is loading the page. Once the page is loaded, updating or creating an mpld3 figure using an ajax call won't create the figure for you. I personally struggled with that for some time and then gave up. I am sure one can patch things up but then you'll be stuck to your own mpld3 patched version