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

huangapple go评论110阅读模式
英文:

Matplotlib how to draw vertical line between two Y points

问题

我可以使用以下代码连接每个y点对来生成所需的输出:

  1. import matplotlib.pyplot as plt
  2. x = [0, 2, 4, 6]
  3. y = [(1, 5), (1, 3), (2, 4), (2, 7)]
  4. # Extract individual y values
  5. y1 = [i for (i, j) in y]
  6. y2 = [j for (i, j) in y]
  7. plt.plot(x, y1, 'rs', markersize=4)
  8. plt.plot(x, y2, 'bo', markersize=4)
  9. # Connect the y point pairs with thin lines
  10. for i in range(len(x)):
  11. plt.plot([x[i], x[i]], [y1[i], y2[i]], 'k-', lw=1)
  12. plt.xlim(xmin=-3, xmax=10)
  13. plt.ylim(ymin=-1, ymax=10)
  14. plt.xlabel('ID')
  15. plt.ylabel('Class')
  16. plt.show()

这将创建连接每个y点对的细线,生成所需的输出图形。

英文:

I have 2 y points for each x points. I can draw the plot with this code:

  1. import matplotlib.pyplot as plt
  2. x = [0, 2, 4, 6]
  3. y = [(1, 5), (1, 3), (2, 4), (2, 7)]
  4. plt.plot(x, [i for (i,j) in y], 'rs', markersize = 4)
  5. plt.plot(x, [j for (i,j) in y], 'bo', markersize = 4)
  6. plt.xlim(xmin=-3, xmax=10)
  7. plt.ylim(ymin=-1, ymax=10)
  8. plt.xlabel('ID')
  9. plt.ylabel('Class')
  10. plt.show()

This is the output:

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

How can I draw a thin line connecting each y point pair? Desired output is:

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

答案1

得分: 9

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

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

英文:

just add
plt.plot((x,x),([i for (i,j) in y], [j for (i,j) in y]),c='black')

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

答案2

得分: 4

你也可以使用 LineCollection。下面的解决方案改编自 这个 回答。

  1. from matplotlib import collections as matcoll
  2. x = [0, 2, 4, 6]
  3. y = [(1, 5), (1, 3), (2, 4), (2, 7)]
  4. lines = []
  5. for i, j in zip(x, y):
  6. pair = [(i, j[0]), (i, j[1])]
  7. lines.append(pair)
  8. linecoll = matcoll.LineCollection(lines, colors='k')
  9. fig, ax = plt.subplots()
  10. ax.plot(x, [i for (i, j) in y], 'rs', markersize=4)
  11. ax.plot(x, [j for (i, j) in y], 'bo', markersize=4)
  12. ax.add_collection(linecoll)

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

英文:

Alternatively, you can also use LineCollection. The solution below is adapted from this answer.

  1. from matplotlib import collections as matcoll
  2. x = [0, 2, 4, 6]
  3. y = [(1, 5), (1, 3), (2, 4), (2, 7)]
  4. lines = []
  5. for i, j in zip(x,y):
  6. pair = [(i, j[0]), (i, j[1])]
  7. lines.append(pair)
  8. linecoll = matcoll.LineCollection(lines, colors='k')
  9. fig, ax = plt.subplots()
  10. ax.plot(x, [i for (i,j) in y], 'rs', markersize = 4)
  11. ax.plot(x, [j for (i,j) in y], 'bo', markersize = 4)
  12. ax.add_collection(linecoll)

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

huangapple
  • 本文由 发表于 2020年1月4日 01:04:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/59582503.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定