4
votes

I am having trouble connecting two sets of points in a scatter plot with each other such that a line (in this example, using dummy data) connects all the 'pre' points with the corresponding 'post' points. The 'marker = 'o-' argument doesn't work for plt. scatter, but does for plt. plot. Suggestions on how to connect the corresponding values? Thanks and hope this question makes sense!

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()
1
Maybe you're overthinking this. for i in range(len(x1)): plt.plot([x1[i],x2[i]], [y1[i],y2[i]]) - ImportanceOfBeingErnest
yes, this worked great! I also added marker = 'o' so the end points would appear. Thanks! - Anna

1 Answers

2
votes

While @ImportanceOfBeingErnest already gave you the seemingly simplest possible solution, you might be interested in knowing an alternate solution to get what you want. You can use 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