1

I am learning the matplotlib. But I can not understand the example in their official page.

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 10)
line, = plt.plot(x, np.sin(x), '--', linewidth=2)

dashes = [10, 5, 100, 5] # 10 points on, 5 off, 100 on, 5 off
line.set_dashes(dashes)

plt.show()

The result is

result
(source: matplotlib.org)

Question about the code is:

line, = plt.plot(x, np.sin(x), '--', linewidth=2)

What means the "," after the line?

Thanks very much for the patient!

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
xirururu
  • 5,028
  • 9
  • 35
  • 64

2 Answers2

2

A good place to start for these sorts of questions is always the documentation. Here's the docs for pyplot.plot(). Note that about halfway down it says:

Return value is a list of lines that were added.

So the example uses line, instead of line in order to select just the first element in the returned list (which also happens to be the only element in this case). You can check this out for yourself:

line, = plt.plot(x, np.sin(x), '--', linewidth=2)

type(line)
Out[59]: matplotlib.lines.Line2D

So line is a Line2D object. However, when we omit the comma:

line = plt.plot(x, np.sin(x), '--', linewidth=2)

We get:

type(line)
Out[61]: list

line
Out[62]: [<matplotlib.lines.Line2D at 0x7f9a04060e10>]

So in this case line is actually a list that contains one Line2D object.

Here is the documentation for Line2D.set_dashes(); see if that answers your other question.

James Kelleher
  • 1,957
  • 3
  • 18
  • 34
1

The

,

generally is to create a tuple.

You can see here a detailed explanation.

Community
  • 1
  • 1
George
  • 5,808
  • 15
  • 83
  • 160