3

Can someone explain this behaviour?

import matplotlib.pyplot as plt
plt.plot(x=[0.05, 0.1, 0.15], y=[102, 211, 393])
plt.show()

No output!

import matplotlib.pyplot as plt
plt.plot([0.05, 0.1, 0.15], [102, 211, 393])
plt.show()

With output!

That is, without specifying x= and y= explicitly, pyplot works fine. However, this is different from the behaviour in the documentation. Well, the documentation does not explicitly use x= or y=, but it gives the signature of plot as plot(x, y). Therefore, named arguments should be permitted, and produce the same result, right?

3 Answers 3

3

I think the confusion comes from the difference in signatures. This is a python problem.

Consider

def func1(x,y):
    print(x,y)

def func2(*args):
    print(args)

You may call each of them with positional arguments.

func1(1,2)
func2(1,2)

You may also call the first function with named arguments.

func1(x=1, y=2)

However, you cannot call the second function with named arguments, because x and y are not defined.

func2(x=1, y=2)

results in an Error.

As seen from the documentation of plot, it uses the second way of defining the function,

matplotlib.pyplot.plot(*args, **kwargs)

I think the matplotlib documentation needs to assume some basic python understanding, but if there is something that can be done to clarify it, feel free to reach out with a suggestion on what to improve.

Sign up to request clarification or add additional context in comments.

Comments

2

If you look at the source code for plot , it goes something like this:

def plot(*args, **kwargs):
...

The documentation does it make it clear that x,y arrays are mandatory , but if you pass x=[],y=[] , the plot function would recognise them as parts of kwargs and not the args. Plot expects two arrays as direct arguments without which it returns an empty object set. These links would tell you more about them:

https://pythontips.com/2013/08/04/args-and-kwargs-in-python-explained/ https://www.geeksforgeeks.org/args-kwargs-python/

Comments

1

Nowhere in the documentation does it show the use of keyword arguments. If you follow the source code you see that the plot data arguments are handled by _process_plot_var_args(object) in quite an involved way. Hence, the behavior you observe is not a bug.

Instead, quite interestingly, this design allows you to do the following:

plt.plot(x1, y1, "r--", x2, y2, "bo")

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.