首页 > 解决方案 > 给现有的 matplotlib 轴对象 kwargs

问题描述

我想给一个现有的轴对象一个关键字参数字典。这可能吗?

即类似的东西

import matplotlib.pyplot as plt

kwargs = {'xlim':(0, 2), 'ylabel':'y'}

fig, ax = plt.subplots()
ax.give_kwargs(**kwargs)

我看到这个matplotlib.Axes类有一个**kwargs参数,但是(我很确定)它只在对象初始化期间可用,而不是在对象已经存在之后。

编辑:

为了避免XY 问题,这里是想要做这样的事情的背景。

我发现自己经常做的是创建绘制一些通用数据的函数,我必须添加 5 个以上的额外参数来处理轴的所有“设置”方法:

def fancy_plot(data_arg1, dataarg2, xlim=None, ylabel=None):

    fig, ax = plt.subplots()
    ax.plot(data[data_arg1], data[data_arg2])

    if xlim: ax.set_xlim(xlim)
    if ylabel: ax.set_ylabel(ylabel)

标签: matplotlib

解决方案


是的,我们可以将您kwargs的字典视为方法和参数的字典。

import matplotlib.pyplot as plt

kwargs = {'set_xlim': (0, 2), 'set_ylabel': 'y'}

fig, ax = plt.subplots()
for (method, arguments) in kwargs:
    getattr(ax, method)(*arguments)

或者,如果所有方法都遵循set_something命名约定:

import matplotlib.pyplot as plt

kwargs = {'xlim': (0, 2), 'ylabel': 'y'}

fig, ax = plt.subplots()
for (method, arguments) in kwargs:
    getattr(ax, f"set_{method}")(*arguments)

然后,您可以将该getattr部分包装在 atry-except中,以防您的字典包含不是现有ax方法的名称。

for (method, arguments) in kwargs:
    try:
        getattr(ax, f"set_{method}")(*arguments)
    except AttributeError:
        print("Please everyone panic.")

推荐阅读