1

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()

4 Answers 4

4

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()
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

2

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)

Comments

1

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'})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.