设置 matplotlibs 线型的 space 大小 "dashed"

Set the space size of matplotlibs linestyle "dashed"

在使用 linestyle "dashed" 绘图时,有什么方法可以在连续的破折号之间设置 space size/thickness 吗? 我正在寻找的是可以自由地使用以下线型进行绘图:

-----
-  -  -  -
-     -     -    -

下面包含一小段代码。我在想这将是线型选项的问题。但是,找不到它,也不在 SO 的存档中。

import numpy

x = numpy.linspace(0, 100, 101)
y = x

plt.plot(x, y, "r", linestyle = "dashed")
plt.show()

Line2D 实例有 属性 dashes,这是一个数字序列。第一项是第一个 on-segment 的长度(以磅为单位),第二个是 off-segment,第三个是 on-segment,依此类推。该序列在整个线路长度上循环。

所以(10,5)表示:上墨10分,下墨5分,依此类推...

给你:

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 100, 101)
y = x

plt.plot(x, y, "r", linestyle = "dashed", dashes=(10,5)) # short gap
plt.plot(x, y+5, "r", linestyle = "dashed", dashes=(10,20)) # long gap
plt.plot(x, y+10, "r", linestyle = "dashed", dashes=(5,5,5,5,5,15,15,5,15,5,15,15,5,5,5,5,5,35)) # SOS
plt.show()

您可以为您的行指定一系列 on/off 破折号,如下所示:

import numpy
import matplotlib.pyplot as plt

x = numpy.linspace(0, 100, 101)
y = x

plt.plot(x, y, "r", linestyle="dashed", dashes=[3, 1, 2, 8])
plt.show()

这意味着在循环重复之前,该行将是“3 条破折号,1 条破折号,2 条破折号和 8 条破折号”。您可以根据需要自定义传入的顺序。