Python 和 Matplotlib : How to pass dict to functions?

标签 python matplotlib

我正在制作一个自定义绘图配置函数 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()

关于Python 和 Matplotlib : How to pass dict to functions?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37585863/

相关文章:

python - 使用来自 python 2.4 的输入重定向运行 shell 命令?

python - 在 tensorflow 中实现 3D 卷积的最佳方式是什么?

python - 如何从单独的进程(例如,编辑器、vim)在 Jupyter Notebook 服务器中创建和执行单元格?

python - 丢弃数据报套接字的传入 'packets'

python - 在 matplotlib 中传递用于绘图的元组会在第 10 行抛出 "Tuple Object is not callable"错误。 3个

Python matplotlib : how to let matrixplot have variable column widths

python - 在 pylab.plot 中使用数据框列名作为标签

python - Docker-Compose HAProxy缺少前端

matplotlib - 将颜色条的标签从增加值更改为减少值

Python:加权 fiddle 图