python - Matplotlib python 用每对 (x,y) 值的线连接两个散点图?

标签 python matplotlib scatter-plot

我在将散点图中的两组点相互连接时遇到问题,这样一条线(在本例中使用虚拟数据)将所有“前”点与相应的“后”点连接起来。 'marker = 'o-' 参数不适用于 plt。分散,但对 plt 有效。阴谋。关于如何连接相应值的建议?谢谢,希望这个问题有意义!

import matplotlib.pyplot as plt
import numpy as np
x1 = ["pre"] * 4
x2 = ["post"] * 4
y1 = [0.1, 0.15, 0.13, 0.25]
y2 = [0.85, 0.76, 0.8, 0.9]
plt.scatter(x1, y1, color='y')
plt.scatter(x2, y2, color='g')
plt.show()

最佳答案

虽然@ImportanceOfBeingErnest 已经为您提供了看似最简单的可能解决方案,但您可能有兴趣了解替代解决方案以获得您想要的结果。您可以使用 LineCollection

from matplotlib.collections import LineCollection

fig, ax = plt.subplots()

# Rest of your code

lines = [[x, list(zip([1]*4, y2))[i]] for i, x in enumerate(zip([0]*4, y1))]
print (lines)
# [[(0, 0.1), (1, 0.85)], [(0, 0.15), (1, 0.76)], [(0, 0.13), (1, 0.8)], [(0, 0.25), (1, 0.9)]]

lc = LineCollection(lines)
ax.add_collection(lc)
plt.show()

enter image description here

关于python - Matplotlib python 用每对 (x,y) 值的线连接两个散点图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54659559/

相关文章:

python - 使用带修饰协程的单个事件循环返回 future 结果

python - pandas 合并以从数据框中取出两列并对列进行操作

python - 使用 pandas 和 Matplotlib 自定义日期时间索引的分组条形图

r - 在点图上画圆圈以标记 ggplot2 中的最佳区域

python - 在 Bokeh 中调整 matplotlib 标记大小?

python - Emacs不同框架中的不同python venv

python - 图像定位 OpenCV

python - 使用 %matplotlib 内联时,Jupyter 笔记本 Canvas 无法交互

python - pandas 中多个子图直方图的对数刻度

plot - 如何创建带标签的散点图?