简体   繁体   English

如何从 function 返回 matplotlib 图?

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

I need to plot changing molecule numbers against time.我需要 plot 随时间改变分子数。 But I'm also trying to investigate the effects of parallel processing so I'm trying to avoid writing to global variables.但我也在尝试研究并行处理的影响,所以我试图避免写入全局变量。 At the moment I have the following two numpy arrays tao_all , contains all the time points to be plotted on the x-axis and popul_num_all which contains the changing molecule numbers to be plotted on the y-axis.目前我有以下两个 numpy arrays tao_all ,包含要在 x 轴上绘制的所有时间点和popul_num_all ,其中包含要在 y 轴上绘制的变化的分子数。

The current code I've got for plotting is as follows:我绘制的当前代码如下:

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()

I need to encapsulate this in a function that takes the above arrays as the input and returns the graph.我需要将它封装在一个 function 中,它将上述 arrays 作为输入并返回图形。 I've read a couple of other posts on here that say I should write my results to an axis and return the axis?我在这里阅读了其他几篇文章,说我应该将结果写入轴并返回轴? But I can't quite get my head around applying that to my problem?但是我无法完全理解将其应用于我的问题?

Cheers干杯

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

Usage:用法:

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

Alternatively you may want to return ax .或者,您可能想要返回ax For details about Figure and Axes see the docs .有关 Figure 和 Axes 的详细信息,请参阅文档 You can get the axes array from the figure by fig.axes and the figure from the axes by ax.get_figure() .您可以通过fig.axes从图形中获取轴数组,并通过ax.get_figure()从轴中获取图形。

In addition to above answer, I can suggest you to use matplotlib animation.FuncAnimation method if you are working with the time series and want to make your visualization better.除了上述答案之外,如果您正在使用时间序列并希望使您的可视化效果更好,我可以建议您使用 matplotlib animation.FuncAnimation 方法。

You can find the details here https://matplotlib.org/api/_as_gen/matplotlib.animation.FuncAnimation.html你可以在这里找到详细信息https://matplotlib.org/api/_as_gen/matplotlib.animation.FuncAnimation.html

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

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