使用 Matplotlib 的多个函数绘制为 1 个图形,Python

Plotting to 1 figure using multiple functions with Matplotlib, Python

我有一个主程序 main.py,我在其中调用了各种函数,每个函数都将某些内容绘制成 1 个图形。即所有功能图都将详细信息附加到 1 个主图。

目前我将其设置为,例如:

main.py:

import matplotlib.pylab as plt    

a,b,c = 1,2,3

fig = func1(a,b,c)

d,e,f = 4,5,6

fig = func2(d,e,f)

plt.show()

func1:

def func1(a,b,c):
    import matplotlib.pylab as plt
    ## Do stuff with a,b and c ##
    fig = plt.figure()    
    plt.plot()
    return fig

func2:

def func2(d,e,f):
    import matplotlib.pylab as plt
    ## Do stuff with d,e and f ##
    fig = plt.figure()    
    plt.plot()
    return fig

这种方法已经完成了一半,但它为每个函数绘制了单独的图形,而不是叠加它们。

如何获得一张图,所有图的结果相互叠加?

这应该有效。请注意,我只创建了一个图形并使用 pyplot 接口绘制它,而没有明确获得对图形对象的引用。

import matplotlib.pyplot as plt    

a = [1,2,3]
b = [3,2,1]

def func1(x):
    plt.plot(x)

def func2(x):
    plt.plot(x)

fig = plt.figure()
func1(a)
func2(b)

这个程序最好使用OO接口。参见 http://matplotlib.org/faq/usage_faq.html#coding-styles

import matplotlib.pyplot as plt    

a = [1,2,3]
b = [3,2,1]

def func1(ax, x):
    ax.plot(x)

def func2(ax, x):
    ax.plot(x)

fig, ax = plt.subplots()
func1(ax, a)
func2(ax, b)

像这样简单的功能看起来很傻,但是当你想做更复杂的事情时,遵循这种风格会让事情变得不那么痛苦。