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:
JavaScript
x
5
1
def plotting_function():
2
fig, ax = plt.subplots()
3
ax.plot([1,2,3], [2,4,10])
4
return fig
5
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:
JavaScript
1
6
1
fig, axs = plt.subplots(1,3)
2
for i in range(3):
3
plt.sca(axs[i])
4
plotting_function()
5
plt.show()
6
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:
JavaScript
1
32
32
1
import matplotlib.pyplot as plt
2
from matplotlib.transforms import Bbox
3
4
5
def plotting_function1():
6
fig, ax = plt.subplots()
7
ax.plot([1,2,3], [2,4,10])
8
return fig
9
10
def plotting_function2():
11
fig, ax = plt.subplots()
12
ax.plot([10,20,30], [20,40,100])
13
return fig
14
15
def main():
16
f1 = plotting_function1()
17
ax1 = plt.gca()
18
ax1.remove()
19
20
f2 = plotting_function2()
21
ax2 = plt.gca()
22
ax1.figure = f2
23
f2.axes.append(ax1)
24
f2.add_axes(ax1)
25
26
# These positions are copied from a call to subplots().
27
ax1.set_position(Bbox([[0.125, 0.11], [0.477, 0.88]]))
28
ax2.set_position(Bbox([[0.55, 0.11], [0.9, 0.88]]))
29
plt.show()
30
31
main()
32