matplotlib - 给现有的 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)
解决方案
是的,我们可以将您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.")
推荐阅读
- algorithm - 中位数的有效算法
- java - 在 AnyLogic 的汇编程序块中配置“新代理”
- ubuntu - 错误消息:安装 OpenDaylight “java_home”
- r - 我们应该根据以下描述在逻辑回归中包含还是排除变量?
- version-control - 带有附加源控制存储库的 Composer 依赖项
- angular - 如何从 TypeScript 中的麦克风获取 PCM?
- algorithm - 给定一个整数集合和阈值 T,将集合划分为尽可能多的总和 >= T 的组
- css - 表格行上的CSS动画如何影响高度
- android - 反应原生 gradle 构建失败:“node -e console.log(require('react-native/cli').bin);” : 命令失败
- python-3.x - 编辑 xmp 标签 pyexiv2 modify_xmp 不能正确替换 xmp 标签