1

I'm trying to make a Voronoi plot update in real time as the generating points change position.

My problem is how to reuse the same figure, since currently I get a new window each time I call voronoi_plot_2d.

See code:

#!/usr/bin/env python

import numpy as np
import time
from scipy.spatial import Voronoi, voronoi_plot_2d
import matplotlib.pyplot as plt


plt.ion()
(x,y) = (1,2)
plt.show()


while True:
    print "loop "
    x += 0.1
    y += 0.1
    points = np.array([[0, 0], [1, 3], [0, 2.5], [x,y], [4, 1], [6, 4]])
    vor = Voronoi(points)
    apa = voronoi_plot_2d(vor)
    time.sleep(0.5)

I got some ideas for this from

http://docs.scipy.org/doc/scipy-0.15.1/reference/generated/scipy.spatial.Voronoi.html

real-time plotting in while loop with matplotlib

Community
  • 1
  • 1
user985366
  • 1,635
  • 3
  • 18
  • 39

1 Answers1

1

The code in the guide can be used to acheive this.

http://docs.scipy.org/doc/scipy/reference/tutorial/spatial.html

I haven't yet had time to read through and understand all the code, but it "manually" does what I want and it works.

Instead of using

voronoi_plot_2d(vor)

It step by step uses the different parts of vor to plot the voronoi plot, and this can be repeated in the loop. Full code example below:

#!/usr/bin/env python

import numpy as np
import time
from scipy.spatial import Voronoi, voronoi_plot_2d
import matplotlib.pyplot as plt


plt.ion()
(x,y) = (1,2)
plt.draw()


while True:
    print "loop "
    x += 0.1
    y += 0.1
    points = np.array([[0, 0], [1, 3], [0, 2.5], [x,y], [4, 1], [6, 4]])
    plt.clf()
    vor = Voronoi(points)

####MANUAL PLOTTING

    plt.plot(points[:,0], points[:,1], 'o')
    plt.plot(vor.vertices[:,0], vor.vertices[:,1], '*')
    plt.xlim(-1, 3); plt.ylim(-1, 3)


    for simplex in vor.ridge_vertices:
        simplex = np.asarray(simplex)
        if np.all(simplex >= 0):
            plt.plot(vor.vertices[simplex,0], vor.vertices[simplex,1], 'k-')

    center = points.mean(axis=0)
    for pointidx, simplex in zip(vor.ridge_points, vor.ridge_vertices):
        simplex = np.asarray(simplex)
        if np.any(simplex < 0):
            i = simplex[simplex >= 0][0] # finite end Voronoi vertex
            t = points[pointidx[1]] - points[pointidx[0]] # tangent
            t /= np.linalg.norm(t)
            n = np.array([-t[1], t[0]]) # normal
            midpoint = points[pointidx].mean(axis=0)
            far_point = vor.vertices[i] + np.sign(np.dot(midpoint - center, n)) * n * 100
            plt.plot([vor.vertices[i,0], far_point[0]], [vor.vertices[i,1], far_point[1]], 'k--')
    plt.draw()
    time.sleep(0.5)
user985366
  • 1,635
  • 3
  • 18
  • 39