Passing x- and y-data as keyword arguments in matplotlib?

Or why not

import numpy import matplotlib.pyplot as plt plt.plot(xdata = numpy.array([1]), ydata = numpy.array(1), color = 'red', marker = 'o') 

work? cf

 > In [21]: import numpy > In [22]: import matplotlib.pyplot as plt > In [23]: plt.plot(xdata = numpy.array([1]), ydata = numpy.array(1), color = 'red', marker = 'o') > Out[23]: [] > In [24]: plt.plot([1],[1], color = 'red', marker = 'o') > Out[24]: [<matplotlib.lines.Line2D at 0x108036890>] > In [25]: plt.plot(1, 1, color = 'red', marker = 'o') > Out[25]: [<matplotlib.lines.Line2D at 0x1041024d0>] 
+4
source share
2 answers

Just to expand on what @Yann already said:

To understand why this happens, you need to understand a little about the structure of matplotlib. To enable "matlab-isms" like plt.setp and maintain compatibility with older versions of python, matplotlib avoids properties and relies heavily on getters and setters. ( plot is actually one of the most difficult cases, simply because of all the crazy calling forms that it supports).

You can make a good argument that this is an outdated, non-reptile design, but that is irrelevant.

What actually happens (for the simplest case, plot(x, y, other=stuff) ) when plot is called is that a new matplotlib.line.Line2D object is created from the first two arguments, and then matplotlib.line.Line2D.update(kwargs) is matplotlib.line.Line2D.update(kwargs) .

update basically:

 for key, value in kwargs.iteritems(): func = getattr(self, 'set_'+key) func(value) 

I simplify too much, but this is the main idea.

Also, the accepted keyword argument list is basically auto- set_* from everything that has set_* . Because Line2D has the set_xdata and set_ydata , they appear in the keyword argument list.

The fact is that keyword arguments are never used until after more initialization of Line2D , and if you do not specify any arguments, plot will not initialize any Line2D .

You may consider this a mistake, but I doubt it will be fixed. I do not think that xdata and ydata were ever intended to be used as keyword arguments.

set_xdata and set_ydata so you can quickly update an instance of Line2D instead of creating a new one (for animation, etc.). They are simply allowed as keyword arguments due to the way matplotlib is configured.

+9
source

Why? Who knows, but it seems that the line is not created if you do not specify the arguments x and y . xdata and ydata modify the given lines only if they are created, and it seems that they are not created without parameters. Try the following:

 plt.plot([0],[0],xdata = [1,2,3,4], #numpy.array([3,4]), ydata = [4,5,6,7], #numpy.array([3,4]), color = 'red', marker = 'o') 

It works the way I think you intend to do it.

+3
source

Source: https://habr.com/ru/post/1392557/


All Articles