【问题标题】:Matplotlib how to draw vertical line between two Y pointsMatplotlib如何在两个Y点之间绘制垂直线
【发布时间】:2020-01-05 21:49:21
【问题描述】:

每个 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 点对的细线?期望的输出是:

【问题讨论】:

    标签: python matplotlib plot scatter-plot


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      或者,您也可以使用LineCollection。以下解决方案改编自this答案。

      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)
      

      【讨论】: