Skip to main content
 首页 » 编程设计

Python 和 Matplotlib : How to pass dict to functions

2025年05月04日10shanyou

我正在制作一个自定义绘图配置函数 plt_configure,因此我可以将标签、图例和其他绘图选项与一个命令组合在一起。

对于图例,我想做类似的事情:

plt_configure(legend={loc: 'best'}) 
# => plt.legend(loc='best') 
plt_configure(legend=True) 
# => plt.legend() 

那函数应该怎么定义呢?

现在我将函数定义为:

def plt_configure(xlabel='', ylabel='', legend=False): 
    plt.xlabel(xlabel) 
    plt.ylabel(ylabel) 
    if legend: 
        # if legend passed as options 
            plt.legend(options) 

或者我的功能设计不好,考虑以上两种情况,什么是好的设计? # 别的 plt.图例()

请您参考如下方法:

空字典的计算结果为 False,非空字典的计算结果为 True。因此,无论 legend 是字典还是 bool 值,您都可以使用 if legend。

然后你可以测试legend是否是一个dict,并将它传递给plt.legend

def plt_configure(xlabel='', ylabel='', legend=False): 
    plt.xlabel(xlabel) 
    plt.ylabel(ylabel) 
    if legend: 
        if isinstance(legend, dict): 
            plt.legend(**legend) 
        else: 
            plt.legend()