绘制具有多种线型的一条线

Plot one line with multiple line styles

数据:

x = 300, 300, 300, 300, 300

y = 1200, 900, 200, -600, -1371

我已经使用 plt.plot(x, y, marker='s', linestyle='dotted') 用 matplotlib 绘图,但它只显示一种样式。

如果我想用两种不同的线型制作线图,从 (300,1200) 到 (200,300) 的实线样式,然后其余的点缀,是否可以。

请帮忙。谢谢

正如我在评论中所述,您需要像这样拆分数据:

x_dotted = x[3:]
y_dotted = y[3:]

x_solid = x[:3]
y_solid = y[:3]

然后只需使用您想要的参数调用 plt.plot

我觉得this answer is good for your question. I tried to modify it for line styles. For more information read about LineCollection.

import numpy as np
from matplotlib.collections import LineCollection
import matplotlib.pyplot as plt


x = np.array([300, 300, 300, 300, 300])
y = np.array([1200, 900, 200, -600, -1371])


points = np.array([x, y]).T.reshape(-1, 1, 2)


segments = np.concatenate([points[:3], points[-3:]], axis=1)
line_styles = [("dashed"),("solid")]

lc = LineCollection(segments, linestyles=line_styles, color='black')

fig,a = plt.subplots()
a.add_collection(lc)
a.set_xlim(0,500)
a.set_ylim(-1500,1500)
plt.show()