5

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()
Anna
  • 51
  • 1
  • 2

1 Answers1

2

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

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
Sheldore
  • 37,862
  • 7
  • 57
  • 71
  • Overkill or duplicate? – ImportanceOfBeingErnest Feb 12 '19 at 23:50
  • I here had to figure out how to create the list lines here. Rest was based on using linecollection from SO. I admit it’s an overkill and that’s why I started my answer saying that your suggestion was the easiest yet this is just an alternative. To Be honest, I actually was myself interested in trying to see how one can use line collection in solving this problem ;) – Sheldore Feb 13 '19 at 00:01
  • Hmm, so if this is a question, I'd do `verts = np.c_[np.zeros_like(y1),y1,np.ones_like(y2),y2].reshape(len(x1),2,2)` – ImportanceOfBeingErnest Feb 13 '19 at 00:19