是否可以使用python和matplotlib在用户定义的函数中绘图?

Fxy*_*ang 5 python matplotlib

我想要做的是定义一个包含绘图句子的函数.像这样:

import matplotlib.pyplot as plt

def myfun(args, ax):
    #...do some calculation with args
    ax.plot(...)
    ax.axis(...)

fig.plt.figure()
ax1=fig.add_subplot(121)
ax2=fig.add_subplot(122)
para=[[args1,ax1],[args2,ax2]]
map(myfun, para)
Run Code Online (Sandbox Code Playgroud)

我发现myfun被称为.如果我在myfun中添加plt.show(),它可以在正确的子图中绘图,但在另一个子图中没有任何内容.并且,如果最后添加了plt.show(),则只绘制两对轴.我认为问题是图形没有成功转移到主函数.有可能用python和matplotlib做这样的事情吗?谢谢!

fal*_*tru 6

通过map调用的函数应该只有一个参数.

import matplotlib.pyplot as plt

def myfun(args):
    data, ax = args
    ax.plot(*data)

fig = plt.figure()
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)
para = [
    [[[1,2,3],[1,2,3]],ax1],
    [[[1,2,3],[3,2,1]],ax2],
]
map(myfun, para)
plt.show()
Run Code Online (Sandbox Code Playgroud)

如果要保留函数签名,请使用itertools.starmap.

import itertools
import matplotlib.pyplot as plt

def myfun(data, ax):
    ax.plot(*data)

fig = plt.figure()
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)
para = [
    [[[1,2,3],[1,2,3]],ax1],
    [[[1,2,3],[3,2,1]],ax2],
]
list(itertools.starmap(myfun, para)) # list is need to iterator to be consumed.
plt.show()
Run Code Online (Sandbox Code Playgroud)

  • 抱歉。我在我的代码中犯了一个愚蠢的错误(绘图句子不是用我的完整代码编写的属性)。非常感谢。Itertools 真的很有帮助。赞赏。 (2认同)