Matplotlib 加线连接相关散点

Matplotlib add line to connect related scatter points

是否有内置方法可以添加一条连接具有相同 y 值的散点的线?

目前有这个:

x1 = [6, 11, 7, 13, 6, 7.5]
x2 = [np.nan, np.nan, np.nan, np.nan, np.nan, 8.6]
y = [2, 10, 2, 14, 9, 10]
df = pd.DataFrame(data=zip(x1, x2, y), columns=["x1", "x2", "y"])

fig, ax = plt.subplots()
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.scatter(df["x1"], df["y"], c="k")
ax.scatter(df["x2"], df["y"], edgecolor="k", facecolors="none")

想要这个:

您可以使用以下代码迭代地配对点 (x1[i],y[i]) 和 (x2[i],y[i]):


import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

x1 = [6, 11, 7, 13, 6, 7.5]
x2 = [np.nan, np.nan, np.nan, np.nan, np.nan, 8.6]
y = [2, 10, 2, 14, 9, 10]
df = pd.DataFrame(data=zip(x1, x2, y), columns=["x1", "x2", "y"])

fig, ax = plt.subplots()
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.scatter(df["x1"], df["y"], c="k")
ax.scatter(df["x2"], df["y"], edgecolor="k", facecolors="none")
for i in range(len(y)):
  plt.plot([x1[i],x2[i]],[y[i],y[i]])
plt.show()

此代码的输出为: