Matplotlib 如何在两个 Y 点之间绘制垂直线

Matplotlib how to draw vertical line between two Y points

每个 x 点我有 2 个 y 点。我可以用这段代码画图:

import matplotlib.pyplot as plt

x = [0, 2, 4, 6]
y = [(1, 5), (1, 3), (2, 4), (2, 7)]


plt.plot(x, [i for (i,j) in y], 'rs', markersize = 4)
plt.plot(x, [j for (i,j) in y], 'bo', markersize = 4)

plt.xlim(xmin=-3, xmax=10)
plt.ylim(ymin=-1, ymax=10)

plt.xlabel('ID')
plt.ylabel('Class')
plt.show()

这是输出:

如何绘制连接每个 y 点对的细线?期望的输出是:

只需添加 plt.plot((x,x),([i for (i,j) in y], [j for (i,j) in y]),c='black')

或者,您也可以使用 LineCollection. The solution below is adapted from 答案。

from matplotlib import collections as matcoll

x = [0, 2, 4, 6]
y = [(1, 5), (1, 3), (2, 4), (2, 7)]

lines = []
for i, j in zip(x,y):
    pair = [(i, j[0]), (i, j[1])]
    lines.append(pair)

linecoll = matcoll.LineCollection(lines, colors='k')

fig, ax = plt.subplots()
ax.plot(x, [i for (i,j) in y], 'rs', markersize = 4)
ax.plot(x, [j for (i,j) in y], 'bo', markersize = 4)
ax.add_collection(linecoll)