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 theLine2D
objects plotted, even if you plot only one line.That comma is unpacking the single value into
line
.ex
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.
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:Where
line1
would correspond tox,y
, and line2 corresponds tox,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 toor
Your code should work if you omit the comma, only because you are not using
line
. In your simple exampleplt.plot(x,y,'-')
would be enough.