[英]Matplotlib how to draw vertical line between two Y points
I have 2 y points for each x points.每个 x 点我有 2 个 y 点。 I can draw the plot with this code:
我可以用这个代码绘制图:
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()
This is the output:这是输出:
How can I draw a thin line connecting each y point pair?如何绘制连接每个 y 点对的细线? Desired output is:
期望的输出是:
Alternatively, you can also use LineCollection .或者,您也可以使用LineCollection 。 The solution below is adapted from this answer.
下面的解决方案改编自这个答案。
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.