【问题标题】:Redraw plot in same window with scipy / voronoi_plot_2d使用 scipy / voronoi_plot_2d 在同一窗口中重绘绘图
【发布时间】:2015-05-22 18:23:43
【问题描述】:

我正在尝试随着生成点位置的变化实时更新 Voronoi 图。

我的问题是如何重用同一个图形,因为目前我每次调用 voronoi_plot_2d 时都会得到一个新窗口。

见代码:

#!/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)

我从

那里得到了一些想法

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

real-time plotting in while loop with matplotlib

【问题讨论】:

    标签: python numpy matplotlib scipy voronoi


    【解决方案1】:

    指南中的代码可用于实现这一目标。

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

    我还没有时间通读和理解所有代码,但它“手动”完成了我想要的工作。

    而不是使用

    voronoi_plot_2d(vor)
    

    它逐步使用 vor 的不同部分来绘制 voronoi 图,并且可以在循环中重复此操作。完整代码示例如下:

    #!/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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-24
      • 2011-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多