繁体   English   中英

使用 Matplotlib、Python 的多个函数绘制到 1 个图形

[英]Plotting to 1 figure using multiple functions with Matplotlib, Python

我有一个主程序main.py ,我在其中调用了各种函数,其想法是每个函数都将某些内容绘制为 1 个数字。 即所有函数图都将细节附加到 1 主图。

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

主要.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()

功能1:

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

功能2:

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

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

如何获得 1 个图形,其中所有图的结果相互叠加?

为此目的使用 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)

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

这应该有效。 请注意,我只创建了一个图形并使用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)

阴谋

暂无
暂无

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

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