Search code examples
pythonmatplotlibplotplotly

Matplotlib Figure to an Axis


I have an API that returns a plt.figure(). I call the API three times to generate three different figures.

f1 = plt.figure()
f2 = plt.figure()
f3 = plt.figure()

I want to display them side by side, so I create a new figure like this:

fig, axes = plt.subplots(nrows=1, ncols=3)

How can I populate each of the axes with the plt.figure()s I created via the API?

In short, I want to populate these:

enter image description here


Solution

  • You are trying to embed a figure into another figure, see here. I think this would be possible albeit without proper support through matplotlib without delving into te innermechanism of the package. I would suggest recreating the subplots by extracting the data. If the data is tied to the figures itself one could extract the data from the axes itself. Assuming the data are in lines a hint could be the following code;

    import matplotlib.pyplot as plt, numpy as np
    
    figs = []
    for _ in range(3):
        fig = plt.figure()
        ax = fig.add_subplot(111)
        ax.set_title(f'Dummy{_}')
        h1 = ax.plot(np.random.rand(10,2))[0]
        figs.append(fig)
    
    
    def update(axes, figs):
        for axi, figi in zip(axes, figs):
            for axj in figi.axes:
                for line in axj.lines:
                    x, y = line.get_data()
                    axi.plot(x, y)
            axi.figure.canvas.draw_idle()
        return axes
    
    print(figs[0].axes[0].lines)
    fig, ax = plt.subplots(1, 3)
    ax[1].set_title('Recreated figure')
    update(ax, figs)
    fig.show()
    

    enter image description here