首页 > 解决方案 > 在 matplotlib 中的图形之间移动绘图

问题描述

我想使用外部函数返回的轴句柄将来自该轴的绘图对象放置在我选择的位于另一个图中的子图中。外部函数的格式不能修改。下面的代码是一个虚拟示例,代表我正在使用的代码的结构。

我希望有一个内置函数来执行此操作,例如 set_figure() 但我找不到。任何帮助表示赞赏。

import matplotlib.pyplot as plt

def myfunc():
    plt.figure()
    plt.text(0.5,0.5,s='plot from\nexternal function')
    return plt.gca()

plt.subplot(311)
plt.text(0.5,0.5,s='subplot 1')

plt.subplot(312)
plt.text(0.5,0.5,s='subplot 2')

plt.subplot(313)
ax = myfunc()
# how can I make the plot generated by myfunc appear in the third subplot
# and close the figure from the external function so it does not show?
plt.show()

所需的输出如下所示:

期望的输出

标签: pythonmatplotlibfigureaxes

解决方案


推荐阅读