I’ve been stumbling around this issue for a while, but today I really want to figure out if it can be done.
Say you have a function from a library that does some plotting, such as:
def plotting_function():
fig, ax = plt.subplots()
ax.plot([1,2,3], [2,4,10])
return fig
If I want to add this single plot multiple times to my own subplots, how could I do this?
I’m not able to change the plotting_function, as it’s from a library, so what I’ve tried is:
fig, axs = plt.subplots(1,3)
for i in range(3):
plt.sca(axs[i])
plotting_function()
plt.show()
This results in an empty subplot with the line graphs plotting separate.
Is there any simple answer to this problem? Thanks in advance.
Advertisement
Answer
I think you might be better off to monkey patch plt.subplots(), but it is possible to move a subplot from one figure to another. Here’s an example, based on this post:
import matplotlib.pyplot as plt
from matplotlib.transforms import Bbox
def plotting_function1():
fig, ax = plt.subplots()
ax.plot([1,2,3], [2,4,10])
return fig
def plotting_function2():
fig, ax = plt.subplots()
ax.plot([10,20,30], [20,40,100])
return fig
def main():
f1 = plotting_function1()
ax1 = plt.gca()
ax1.remove()
f2 = plotting_function2()
ax2 = plt.gca()
ax1.figure = f2
f2.axes.append(ax1)
f2.add_axes(ax1)
# These positions are copied from a call to subplots().
ax1.set_position(Bbox([[0.125, 0.11], [0.477, 0.88]]))
ax2.set_position(Bbox([[0.55, 0.11], [0.9, 0.88]]))
plt.show()
main()