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

时间:2013-06-17 05:39:33

标签: 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)

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

1 个答案:

答案 0 :(得分:5)

通过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()

如果您想保留您的功能签名,请使用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()