matplotlib 2d line line,=plot comma meaning

Question:

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.

Asked By: user2418838

||

Answers:

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, ]
Answered By: tacaswell

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.

Answered By: SethMMorton

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.

Answered By: kindall

in matplotlib documentation https://matplotlib.org/stable/tutorials/introductory/pyplot.html

in ‘Controlling line properties’ section, it gives details about why this comma.
”’
Use the setter methods of a Line2D instance. plot returns a list of Line2D objects; e.g., line1, line2 = plot(x1, y1, x2, y2). In the code below we will suppose that we have only one line so that the list returned is of length 1. We use tuple unpacking with line, to get the first element of that list:
”’

Answered By: lyu
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.