Python&Matplotlib:如何将dict传递给函数?

2024-04-25 00:52:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在生成一个自定义的plot configure函数plt_configure,这样我就可以用一个命令组合label、legend和其他plot选项。在

对于legend,我想做的是:

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

那么我该如何定义函数呢?在

现在我将函数定义为:

^{pr2}$

或者我的功能设计不好,那么什么样的设计才是最好的考虑以上两种情况呢? #其他 plt.图例()


Tags: 函数命令true定义plotconfigure选项情况
3条回答

{{1}如果不是一个关键字,那么就使用一个关键字{1}而不是一个cd2>实例中的关键字

def plt_configure(xlabel='', ylabel='', legend=None):
    plt.xlabel(xlabel)
    plt.ylabel(ylabel)
    if legend and isinstance(legend, dict):
        # get options then...
        plt.legend(options)

Moses Koledoye的回答很好,但是如果你想把额外的选项传递给legend,你也应该把它们传递给你的函数:

def plt_configure(xlabel, ylabel, legend, *args, **kwargs):
    plt.xlabel(xlabel)
    plt.ylabel(ylabel)
    if legend:
        plt.legend(*args, **kwargs)

这样就可以将任意参数和/或关键字传递给legend函数

空字典的计算结果为False,非空字典的计算结果为True。因此,无论if legend是dict还是boolean,都可以使用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()

相关问题 更多 >