Issue
I'd like to give an existing axes object a dictionary of keyword arguments. Is this possible?
ie something like
import matplotlib.pyplot as plt
kwargs = {'xlim':(0, 2), 'ylabel':'y'}
fig, ax = plt.subplots()
ax.give_kwargs(**kwargs)
I see that the matplotlib.Axes
class has a **kwargs
argument, but (I'm pretty sure) that's only available during the initialization of the object, not after the object already exists.
Edit:
To avoid the X Y problem, Here's the background for wanting to do something like this.
What I find myself doing a lot is creating functions that plot some generalized data and I have to add 5+ extra arguments to handle all of the "set" methods for the axes:
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)
Solution
Yes, we can treat your kwargs
dictionnary like a dict of methods and arguments.
import matplotlib.pyplot as plt
kwargs = {'set_xlim': (0, 2), 'set_ylabel': 'y'}
fig, ax = plt.subplots()
for (method, arguments) in kwargs.items():
getattr(ax, method)(*arguments)
Alternatively, if all methods follow the set_something
naming convention:
import matplotlib.pyplot as plt
kwargs = {'xlim': (0, 2), 'ylabel': 'y'}
fig, ax = plt.subplots()
for (method, arguments) in kwargs.items():
getattr(ax, f"set_{method}")(*arguments)
You can then wrap the getattr
part in a try-except
in case your dictionnary contains names that are not existing ax
methods.
for (method, arguments) in kwargs.items():
try:
getattr(ax, f"set_{method}")(*arguments)
except AttributeError:
print("Please everyone panic.")
Answered By - Guimoute
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.