Skip to content Skip to sidebar Skip to footer

Matplotlib Does Not Plot When Named Arguments Are Passed

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() import matplotlib.pyplot as plt plt.plot([0.05, 0.

Solution 1:

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

Consider

deffunc1(x,y):
    print(x,y)

deffunc2(*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.

Solution 2:

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

Solution 3:

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

defplot(*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/

Post a Comment for "Matplotlib Does Not Plot When Named Arguments Are Passed"