Skip to main content
 首页 » 编程设计

python之在 matplotlib hexbin 图中将参数传递给 reduce_C_function

2024年12月31日8lexus

我正在尝试在一个函数内实现一个 hexbin 图,并且有一个相当复杂的 reduce_C_function,它需要接收一个参数 a。一个(尽管微不足道的)例子:

    def sum_i(z,a): 
        return a*np.sum(z) 
    def some_function(X,Y,Z,a): 
        hexb = plt.hexbin(X,Y,C=Z,reduce_C_function=sum_i)

现在,matplotlib 文档 ( https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.hexbin.html ) 并没有提供有关 reduce_C_function 的使用信息,那么我如何设法传递 a 呢?

请您参考如下方法:

你可以制作一个partial从您的 sum_i 函数并将其作为单个参数的函数传递给 plt.hexbin:

from functools import partial 
 
def sum_i(z,a): 
    return a*np.sum(z) 
def some_function(X,Y,Z,a): 
    reduce_function = partial(sum_i, a=a) 
    hexb = plt.hexbin(X,Y,C=Z,reduce_C_function=reduce_function) 

从source code的外观来看没有其他方法可以为 reduce_C_function 传递额外的参数。