Home > Back-end >  Join successive scatter points when in loop matplotlib
Join successive scatter points when in loop matplotlib

Time:08-16

I have a loop of two axes doing a scatter plot with a pause between points.

fig, ax = plt.subplots(2)
for i in range(10):
    y = np.random.random()
    x = np.random.random()
    ax[0].scatter(i, y)
    ax[1].scatter(i, x)
    plt.pause(1)
plt.show()

When I run the code it does a normal scatter plot, I want to be able to join the points with a line. Using plot doesn't work, is there any way to join the successive points? Or do I have to store every previous point in a list and then plot that each time?

CodePudding user response:

Your scatter() call is currently creating a new plot series each time (as seen by different colors of points), so you will not be able to connect these points.

As you already suggested, you can get away with an increasing list:

fig, ax = plt.subplots(2)
x = []
y = []
idx = []
for i in range(10):
    y.append(np.random.random())
    x.append(np.random.random())
    idx.append(i)
    ax[0].plot(idx, y, "bo-")
    ax[1].plot(idx, x, "ro-")
    plt.pause(1)
plt.show()
  • Related