I'm walking through basic tutorials for matplotlib,
and the example code that I'm working on is:
import numpy as np
import matplotlib.pylab as plt
x=[1,2,3,4]
y=[5,6,7,8]
line, = plt.plot(x,y,'-')
plt.show()
Does anyone know what the comma after line (line,=plt.plot(x,y,'-')
) means?
I thought it was a typo but obviously the whole code doesn't work if I omit the comma.
plt.plot
returns a list of the Line2D
objects plotted, even if you plot only one line.
That comma is unpacking the single value into line
.
ex
a, b = [1, 2]
a, = [1, ]
The plot
method returns objects that contain information about each line in the plot as a list. In python, you can expand the elements of a list with a comma. For example, if you plotted two lines, you would do:
line1, line2 = plt.plot(x,y,'-',x,z,':')
Where line1
would correspond to x,y
, and line2 corresponds to x,z
. In your example, there is only one line, so you need the comma to tell it to expand a 1-element list. What you have is equivalent to
line = plt.plot(x,y,'-')[0]
or
line = ply.plot(x,y,'-')
line = line[0]
Your code should work if you omit the comma, only because you are not using line
. In your simple example plt.plot(x,y,'-')
would be enough.
The return value of the function is a tuple or list containing one item, and this syntax "unpacks" the value out of the tuple/list into a simple variable.