pyodide / matplotlib-pyodide

HTML5 backends for Matplotlib compatible with Pyodide
Mozilla Public License 2.0
32 stars 9 forks source link

Matplotlib output using pyodide.runPython() #12

Open hemant-hari opened 5 years ago

hemant-hari commented 5 years ago

I hope this is the right place to put this - how do I access the plots made by the matplotlib package? I am using the pyodide package independent of iodide and I don't know how to use the plots made by matplotlib. I have a similar problem to https://github.com/iodide-project/pyodide/issues/365 but it never received a response. Thanks in advance!

personalizedrefrigerator commented 4 years ago

If self-building Pyodide... Consider subclassing FigureCanvasWasm in pyodide/packages/matplotlib/src/wasm_backend.py and overriding the create_root_element method to create a custom output element. It currently reads:

    # Around line 100 on Nov. 4, 2019...
    def create_root_element(self):
        # Designed to be overridden by subclasses for use in contexts other
        # than iodide.
        try:
            from js import iodide
            return iodide.output.element('div')
        except ImportError:
            return document.createElement('div')

If you do create a custom class, be sure to change the initialization code at the end of wasm_backend.py:

# Around line 580 on 11/4/19
@_Backend.export
class _BackendWasmCoreAgg(_Backend):
    FigureCanvas = FigureCanvasWasm # Change this!
    FigureManager = FigureManagerWasm

    @staticmethod
    def show():
        from matplotlib import pyplot as plt
        plt.gcf().canvas.show()

If unable to modify the source... Given the section of the source included above, it looks like defining some object, iodide, in JavaScript that contains another object, output, with method, element, returning the desired element should work. For example,

    /**
     *  Dummy object to act like that used by Iodide.
     * Only do this if you need to! Bugs related to
     * the successful import of this object might
     * appear!
     */
    window.iodide = 
    {
        output:
        {
            // Create a new element with tagName
            // and add it to an element with id "root".
            element: (tagName) =>
            {
                let elem = document.createElement(tagName);

                document.querySelector("#root").appendChild(elem);

                return elem;
            }
        }
    };