Why can't arguments be passed explicitly as x and y in pyplot?

Viewed 9064

I am using matplotlib.pyplot module imported as plt for plots.

In the plt.plot() statement, if I pass the arguments as "x= array1, "y= array2", I get "TypeError: plot got an unexpected keyword argument 'x' ".

The code gets executed correctly if I simple pass "array1 and array2", without explicitly saying they correspond to x and y axes.

Why is that?

2 Answers

If you look at the function definition, https://github.com/matplotlib/matplotlib/blob/9a24fb724331f50baf0da4d17188860357d328a9/lib/matplotlib/axes/_axes.py#L72, you can see the asterisk there, and the use of that doesn't work with using keywords for non-optional parameters. See Python args and kwargs: Demystified for example.

def plot(self, *args, scalex=True, scaley=True, data=None, **kwargs):
        """
        Plot y versus x as lines and/or markers.
        Call signatures::
            plot([x], y, [fmt], *, data=None, **kwargs)
            plot([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs)

It has to do with the concepts of *args and **kwargs in Python. Both of these let you to use a variable number of parameters within your function, but the difference comes in the fact that while *args takes only the values, **kwargs also takes the keywords as the name "kw" implies.

Since matplotlib.pyplot.plot() function uses *args instead of **kwargs, these functions do not accept keywords within the parameters.

Related