Adding a figure created in a function to another figure's subplot

做~自己de王妃 提交于 2021-01-29 08:27:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!