我正在学习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's the docs for pyplot.plot() 。请注意,大约一半的地方写着:
Return value is a list of lines that were added.
因此,该示例使用 line,
而不是 line
来仅选择返回列表中的第一个元素(在本例中,它也恰好是唯一的元素) )。您可以自己检查一下:
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() ;看看这是否能回答您的其他问题。
关于python - 使用 matplotlib.pyplot.plot 用虚线绘制图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29214707/