在 Python 中将轴作为 **kwarg 传递

Passing axes as **kwarg in Python

我正在构建一个包装器以在 Matplotlib 中生成绘图,我希望能够可选地指定构建绘图的轴。

比如我有:

def plotContourf(thing, *argv, **kwargs):
    return plt.tricontourf(thing[0], thing[1], thing[2], *argv, **kwargs)

def plotScatter(thing, *argv, **kwargs )
    return plt.scatter(thing[0], thing[1], *argv, **kwargs)

fig, ((ax0,ax1),(ax2,ax3)) = plt.subplots(2,2)

plotContourf(some_thing, axes=ax0)
plotScatter(some_thing, axes=ax2)

它运行,但所有内容都绘制在最后一个轴 (ax3) 上,而不是在通过 axes kwargument 指定的轴上。 (这里没有错误,只是出现在错误的轴上)

出于好奇,我想这样做的原因是用户可以设置一个轴,或者对于懒惰的人来说,他们可以在没有指定轴的情况下调用 plotContourf() 并仍然得到他们想要的东西可以 plt.show()

另一方面,我试过

def plotContourf(thing, axes=None, *argv, **kwargs):
    if axes is None:
        fig, axes = plt.subplots()

    return axes.tricontourf(thing[0], thing[1], thing[2], *argv, **kwargs)

但后来我得到:

TypeError: plotContourf() 得到了关键字参数的多个值 'axes'

我知道这个错误是由于 'axes' 已经是一个关键字参数。我知道我可以使用不同的关键字,但是 axes kwarg 有什么用?

谢谢!

编辑: 完整追溯(对于上述第二个选项):

Traceback (most recent call last):
  File "mods.py", line 51, in <module>
    adcirc.plotContourf(hsofs_mesh, -1*hsofs_mesh['depth'], axes=ax0)
TypeError: plotContourf() got multiple values for keyword argument 'axes'

实际包装器:

def plotContourf(grid, axes=None, *argv, **kwargs): 
    if axes is None:
        fig, axes = plt.subplot()
    return axes.tricontourf(grid['lon'], grid['lat'], grid['Elements']-1, *argv, **kwargs)

问题是您使用 -1*hsofs_mesh['depth'] 代替 axes 调用函数,然后在末尾再次添加 axes 关键字参数。

In [10]: def fun(a, x=1, *args, **kwargs):
    ...:     print(x)
    ...:     

In [11]: fun(1, 3, x=4)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-11-31b5e42fb4be> in <module>()
----> 1 fun(1, 3, x=4)

TypeError: fun() got multiple values for keyword argument 'x'

在这个例子中看到它读 3x 然后我传递 x=4。导致您遇到的错误。

一个解决方案是像这样向您的函数添加另一个参数:

def plotContourf(thing, other_thing=None, axes=None, *argv, **kwargs):

您最好将 axes 保留为关键字参数,这样您就无需考虑其他参数的顺序。

import matplotlib.pyplot as plt
import numpy as np

def plotContourf(thing, *argv, **kwargs):
    axes = kwargs.pop("axes", None)
    if not axes:
        fig, axes = plt.subplots()

    return axes.tricontourf(thing[0], thing[1], thing[2], *argv, **kwargs)

a = [np.random.rand(10) for i in range(3)]
plotContourf(a) 

#or

fig, ax = plt.subplots()
plotContourf(a, axes=ax)

plt.show()