繁体   English   中英

如何从 function 返回 matplotlib 图?

[英]How can I return a matplotlib figure from a function?

我需要 plot 随时间改变分子数。 但我也在尝试研究并行处理的影响,所以我试图避免写入全局变量。 目前我有以下两个 numpy arrays tao_all ,包含要在 x 轴上绘制的所有时间点和popul_num_all ,其中包含要在 y 轴上绘制的变化的分子数。

我绘制的当前代码如下:

for i, label in enumerate(['Enzyme', 'Substrate', 'Enzyme-Substrate complex', 'Product']):
    figure1 = plt.plot(tao_all, popul_num_all[:, i], label=label)
plt.legend()
plt.tight_layout()
plt.show()

我需要将它封装在一个 function 中,它将上述 arrays 作为输入并返回图形。 我在这里阅读了其他几篇文章,说我应该将结果写入轴并返回轴? 但是我无法完全理解将其应用于我的问题?

干杯

def plot_func(x, y):
    fig,ax = plt.subplots()
    ax.plot(x, y)
    return fig

用法:

fig = plot_func([1,2], [3,4])

或者,您可能想要返回ax 有关 Figure 和 Axes 的详细信息,请参阅文档 您可以通过fig.axes从图形中获取轴数组,并通过ax.get_figure()从轴中获取图形。

除了上述答案之外,如果您正在使用时间序列并希望使您的可视化效果更好,我可以建议您使用 matplotlib animation.FuncAnimation 方法。

你可以在这里找到详细信息https://matplotlib.org/api/_as_gen/matplotlib.animation.FuncAnimation.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM