0

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

Landmaster
  • 1,043
  • 2
  • 13
  • 21
  • This is not how matplotlib works. Instead create a function that takes an axes as input and plots to that axes. Then, call it either with the single axes from one of your three figures, or with one of the axes of a figure with 4 subplots. – ImportanceOfBeingErnest Oct 02 '19 at 11:48
  • Well this is the way the API was implemented, so I'm trying to find a way to use that API in a nicer way; grouping plots as I've described. – Landmaster Oct 03 '19 at 04:26
  • It's close to impossible for the general case. If your figures only contain certain artists, you might fiddle your way through though. – ImportanceOfBeingErnest Oct 03 '19 at 13:07

1 Answers1

1

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

cvanelteren
  • 1,633
  • 9
  • 16