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

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

Matplotlib how to draw vertical line between two Y points

问题

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

import matplotlib.pyplot as plt

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

# Extract individual y values
y1 = [i for (i, j) in y]
y2 = [j for (i, j) in y]

plt.plot(x, y1, 'rs', markersize=4)
plt.plot(x, y2, 'bo', markersize=4)

# Connect the y point pairs with thin lines
for i in range(len(x)):
    plt.plot([x[i], x[i]], [y1[i], y2[i]], 'k-', lw=1)

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

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

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

英文:

I have 2 y points for each x points. 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:

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。下面的解决方案改编自 这个 回答。

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)

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

英文:

Alternatively, you can also use 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)

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:

确定