问题
I created two functions that make two specific plots and returns me the respective figures:
import matplotlib.pyplot as plt
x = range(1,100)
y = range(1,100)
def my_plot_1(x,y):
fig = plt.plot(x,y)
return fig
def my_plot_2(x,y):
fig = plt.plot(x,y)
return fig
Now, outside of my functions, I want to create a figure with two subplots and add my function figures to it. Something like this:
my_fig_1 = my_plot_1(x,y)
my_fig_2 = my_plot_2(x,y)
fig, fig_axes = plt.subplots(ncols=2, nrows=1)
fig_axes[0,0] = my_fig_1
fig_axes[0,1] = my_fig_2
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?
回答1:
Eaiser and better to just pass your function an Axes
:
def my_plot_1(x,y,ax):
ax.plot(x,y)
def my_plot_2(x,y,ax):
ax.plot(x,y)
fig, fig_axes = plt.subplots(ncols=2, nrows=1)
# pass the Axes you created above
my_plot_1(x, y, fig_axes[0])
my_plot_2(x, y, fig_axes[1])
来源:https://stackoverflow.com/questions/65618035/adding-a-figure-created-in-a-function-to-another-figures-subplot