0

I am trying to learn how to use kwargs via dictionaries as function inputs. As a simple example to learn from, I am trying to make a basic (x,y) plot for which the kwargs can specify the color of the curve and some other plot specs.

import numpy as np
import matplotlib.pyplot as plt

## generate data
f = lambda x : np.array([xi**2 for xi in x]) # function f(x)
x = np.linspace(0, 100)
y = f(x)

## define plotting routine
def get_plot(x, y, kwargs):
    """
    This plot will take multiple kwargs when successful.
    """
    plt.plot(x, y, **kwargs)
    plt.show()

I first try to generate the plot using one kwarg. This works.

plot_dict = dict(color='red')
get_plot(x, y, plot_dict)
>> plot appears 

I then try to generate the plot using two kwargs. This doesn't work.

plot_dict = dict(color='red', xlabel='this is the x-axis')
get_plot(x, y, plot_dict)
>> AttributeError: Unknown property xlabel

But I was under the impression that xlabel is a kwarg because it is a callable arg like color. What is the source of my misunderstanding/mistake?

1 Answer 1

3

Change to this:

def get_plot(x, y, **kwargs):
    """
    This plot will take multiple kwargs when successful.
    """
    plt.plot(x, y, **kwargs)
    plt.show()

and call the function like this: get_plot(x, y, **plot_dict).

Check this tutorial to understand how to use **kwargs.

In nutshell, what **kwargs does, is explode the dictionary into pairs of argument=value, i.e, kwarg1=val1, kwarg2=val2.. instead of you doing that manually.

5
  • I tried that, but I get this error: TypeError: get_plot() takes 2 positional arguments but 3 were given
    – user7345804
    Commented Oct 10, 2017 at 4:10
  • @mikey call it like this: get_plot(x, y, **plot_dict) Commented Oct 10, 2017 at 4:13
  • So I put the double-splat operator ** for a total of three times (twice in the function and once when calling) and I am now getting this error: AttributeError: Unknown property xlabel
    – user7345804
    Commented Oct 10, 2017 at 4:17
  • 1
    @mikey that's because xlabel isn't one of the kwargs supported by matplotlib.pyplot.plot Commented Oct 10, 2017 at 4:23
  • @mikey xlabel is an attribute you set after the plot has been generated: plt.xlabel('label'). matplotlib.org/api/_as_gen/…
    – rayryeng
    Commented Oct 10, 2017 at 4:25