ZK Zhao
ZK Zhao

Reputation: 21523

Python & Matplotlib: How to pass dict to functions?

I'm making a custom plot configure function plt_configure, so I can combine label, legend and other plot options with one command.

For legend, I want to do something like:

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

Then how should I define the function?

Now I define the function as this:

def plt_configure(xlabel='', ylabel='', legend=False):
    plt.xlabel(xlabel)
    plt.ylabel(ylabel)
    if legend:
        # if legend passed as options
            plt.legend(options)

or my function design is bad, what would be a good design to consider the above 2 case? # else plt.legend()

Upvotes: 1

Views: 407

Answers (4)

Serenity
Serenity

Reputation: 36635

I join to early answers, but I think, checking for None have to be in function and you legend dict have to use as kwargs:

def plt_configure(xlabel='', ylabel='', legend=None):
    plt.xlabel(xlabel)
    plt.ylabel(ylabel)
    if not(legend is None): plt.legend(**legend)

...

plt_configure(xlabel='x', ylabel='y', legend={'loc': 'best','mode': 'expand'})

Upvotes: 1

Moses Koledoye
Moses Koledoye

Reputation: 78546

Use None instead in your keyword argument since legend would otherwise be a dict object (not a boolean instance) and then check if the legend is a dictionary instance:

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)

Upvotes: 2

DomTomCat
DomTomCat

Reputation: 8569

Moses Koledoye's answer is fine, however if you want to pass additional options to legend, you'd want to pass them to your function, as well:

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

this way you can pass arbitrary arguments and/or keywords to the legend function

Upvotes: 2

Mel
Mel

Reputation: 6065

An empty dictionary will evaluate to False, a not empty one will evaluate to True. Therefore you can use if legend no matter if legend is a dict or a boolean.

Then you can test if legend is a dict, and pass it to 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()

Upvotes: 4

Related Questions