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

标签 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 做这样的事情?谢谢!

最佳答案

通过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/

相关文章:

python - linux 以太网驱动程序产品 ID、设备 ID 和地址

python - 如何使用 pandas 包为 python 制作的子图清除 boxplot 的默认字幕

python - 正确,Matplotlib 中的 "full length"左右箭头?

python - pyplot 到 3d pdf

Python axhline、标题和轴标签

python - 从 tkinter 标签获取 PhotoImage 对象

python - 在 python 中为 Tor 隐藏服务生成 private_key 和主机名

python - 如何将 pandas 系列中的 'NaN' 字符串转换为 dropna 的空值?

python - Django runserver 报错,全新安装,Django 初次使用者

python - 改变图像的深度?