简体   繁体   English

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

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

I have a main program main.py in which I call various functions with the idea that each function plots something to 1 figure.我有一个主程序main.py ,我在其中调用了各种函数,其想法是每个函数都将某些内容绘制为 1 个数字。 ie all the function plots append detail to the 1 main plot.即所有函数图都将细节附加到 1 主图。

Currently I have it set up as, for example:目前我已将其设置为例如:

main.py:主要.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:功能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

func2:功能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

This approach is halfway there but it plots separate figures for each function instead of overlaying them.这种方法已经完成了一半,但它为每个函数绘制了单独的图形,而不是重叠它们。

How can I obtain 1 figure with the results of all plots overlaid on top of each other?如何获得 1 个图形,其中所有图的结果相互叠加?

It is much better to use the OO interface for this puprose.为此目的使用 OO 接口要好得多。 See http://matplotlib.org/faq/usage_faq.html#coding-styles请参阅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)

It seems silly for simple functions like this, but following this style will make things much much less painful when you want to do something more sophisticated.像这样的简单函数看起来很傻,但是当你想做一些更复杂的事情时,遵循这种风格会让事情变得不那么痛苦。

This should work.这应该有效。 Note that I only create one figure and use the pyplot interface to plot to it without ever explicitly obtaining a reference to the figure object.请注意,我只创建了一个图形并使用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