Python matplotlib drawing figures line by line

Viewed 64

I'm trying to make an animation which will:

  1. Show some points on plotting area
  2. Connect some of these points by straight lines one by one The picture below shows the steps

https://i.stack.imgur.com/4nyN9.png

How can I do it in matplotlib? I have tried smth with:

import numpy as np
import time
from matplotlib import pyplot as plt

data = np.array([
    [-1, 2],
    [2, 3],
    [3, 6],
])
#print(data[0][1])
x, y = data.T

plt.scatter(x,y)
plt.plot()
plt.plot(data[0],data[1],marker='o')
plt.show()
time.sleep(1)
plt.clf()
plt.plot(data[1],data[2],marker='o')
plt.show()
time.sleep(1)
plt.plot(data[2],data[0],marker='o')
plt.show()

but thats not the way to go

@EDIT

Thanks to @mpotes I'm close to the solution.

import matplotlib.pyplot as plt
import numpy as np
import itertools

data = np.array([
    [-1, 2],
    [2, 3],
    [3, 6],
])
x, y = data.T

fig, ax = plt.subplots()
ax.scatter(x,y)

for i in range(len(data)):
    print(data[i])
    if i == len(data)-1:
        print(data[0])
        ax.plot(data[0],data[i],marker='o') #just for a test
    else:
        ax.plot(data[i],data[i+1],marker='o') #just for a test
    ax.set_title("frame {}".format(i))
    # Note that using time.sleep does *not* work here!
    plt.pause(2)

x = input("press x to end")

https://i.stack.imgur.com/Q6cnG.png

But I have a problem with last line. It should connect highest point with the lowest one but idk what it does.

1 Answers

Issue with the last line

  1. plot takes x values and y values as as first and second arguments
  2. here you give mixed values i.e. [x0, y0] and [x2, y2] instead of [x0, x2] and [y0, y2]
  3. this works for first two lines because your values form a symmetric matrix for first two pair of rows in data

I hope you understand the explanation

You need to restructure the data to make array of x values and y values, try:

Code:

import matplotlib.pyplot as plt
import numpy as np

data = np.array([
    [-1, 2],
    [2, 3],
    [3, 6],
])

x, y = data.T
fig, ax = plt.subplots()
ax.scatter(x,y)

for i in range(len(data)):
    if i == len(data)-1:
        x, y = zip(data[0], data[i]) # x = [-1, 3] y = [2, 6]
        ax.plot(x,y,marker='o') #just for a test
    else:
        x, y = zip(data[i], data[i+1])
        ax.plot(x,y,marker='o') #just for a test
    ax.set_title("frame {}".format(i))
    plt.pause(2)

x = input("press x to end")

Output:

enter image description here

Related