使用 matplotlib.pyplot.plot 用虚线绘制图像

use matplotlib.pyplot.plot plot the image with dashed line

我正在学习matplotlib。但是我无法理解他们 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()

结果是


(来源:matplotlib.org

关于代码的问题是:

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

行后的“,”是什么意思?

非常感谢这位患者!

,

一般是创建元组

可以看到here详细的解释

解决此类问题的好起点始终是文档。 Here's the docs for pyplot.plot()。请注意,大约一半的时候它说:

Return value is a list of lines that were added.

因此该示例使用 line, 而不是 line 以便 select 只是返回列表中的第一个元素(在这种情况下它也恰好是唯一的元素) .您可以自己检查一下:

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

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

所以line是一个Line2D对象。但是,当我们省略逗号时:

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

我们得到:

type(line)
Out[61]: list

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

所以在这种情况下 line 实际上是一个包含一个 Line2D 对象的列表。

Here is the documentation for Line2D.set_dashes();看看这是否回答了您的其他问题。