I created two functions that make two specific plots and returns me the respective figures:
JavaScript
x
13
13
1
import matplotlib.pyplot as plt
2
3
x = range(1,100)
4
y = range(1,100)
5
6
def my_plot_1(x,y):
7
fig = plt.plot(x,y)
8
return fig
9
10
def my_plot_2(x,y):
11
fig = plt.plot(x,y)
12
return fig
13
Now, outside of my functions, I want to create a figure with two subplots and add my function figures to it. Something like this:
JavaScript
1
7
1
my_fig_1 = my_plot_1(x,y)
2
my_fig_2 = my_plot_2(x,y)
3
4
fig, fig_axes = plt.subplots(ncols=2, nrows=1)
5
fig_axes[0,0] = my_fig_1
6
fig_axes[0,1] = my_fig_2
7
However, just allocating the created figures to this new figure does not work. The function calls the figure, but it is not allocated in the subplot. Is there a way to place my function figure in another figure’s subplot?
Advertisement
Answer
Eaiser and better to just pass your function an Axes
:
JavaScript
1
12
12
1
def my_plot_1(x, y, ax):
2
ax.plot(x, y)
3
4
def my_plot_2(x, y, ax):
5
ax.plot(x, y)
6
7
fig, axs = plt.subplots(ncols=2, nrows=1)
8
9
# pass the Axes you created above
10
my_plot_1(x, y, axs[0])
11
my_plot_2(x, y, axs[1])
12