我想做的是定义一个包含绘图句子的函数。像这样:
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 做这样的事情?谢谢!
最佳答案
通过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()
关于python - 是否可以使用 python 和 matplotlib 在用户定义的函数中绘图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17141001/