简体   繁体   English

matplotlib:如何返回matplotlib对象然后将其绘制为子图?

[英]matplotlib: How to return a matplotlib object then plot as subplot?

I checked this SO Matplotlib returning a plot object but it does not really fit to my question. 我检查了这个Matplotlib返回一个绘图对象,但它确实不适合我的问题。

What I would like to do is: 我想做的是:

def func1():
   fig1 =  plt.plot (np.arange(0.0, 5.0, 0.1))
   return fig1

def func2()
   return plt.plot (np.arange(0.0, 5.0, 0.02))


fig1 = func1()
fig2 = func2()
plt.figure()
plt.add_subplot(fig1)
plt.add_subplot(fig2)
plt.show()

The above code is just a main idea. 上面的代码只是一个主要思想。 Could you suggest me how to do? 你能建议我怎么做吗?

Thanks 谢谢

The idea would be to let your functions plot to an axes. 想法是让您的函数绘制到一个轴上。 Either you provide this axes as argument to the function or you let it take the current axes. 您可以将此轴提供为函数的参数,或者让它采用当前轴。

import matplotlib.pyplot as plt
import numpy as np

def func1(ax=None):
    ax = ax or plt.gca()
    line, = ax.plot (np.arange(0.0, 5.0, 0.1))
    return line

def func2(ax=None):
    ax = ax or plt.gca()
    line, = ax.plot (np.arange(0.0, 5.0, 0.02))
    return line


fig, (ax1,ax2) = plt.subplots(ncols=2)
func1(ax1)
func2(ax2)

plt.show()

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

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