Python: plot on top of scipy plot? (voronoi)

混江龙づ霸主 提交于 2020-08-09 10:06:18

问题


how do I plot on top of a voronoi plot (which is a scipy plot)? Note my question is slightly different than here where they explain how to color a voronoi plot

For instance, imagine that I have some more points

points = np.array([[1,2], [3,4], [5,6], [7,8]])

after a first voronoi plot. I would like to add them within the existing plot. How do I do that?

The voronoi plot I' referring to is scipy.spatial.voronoi_plot_2d()


回答1:


I think you can simply reuse plot like this:

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

points = np.array([[0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2]])
v = Voronoi(points)
voronoi_plot_2d(v)

p2 = [[0.25, 1], [1, 0.75], [1.75, 0.25], [1.75, 1.75]]
x, y = zip(*p2)

plt.scatter(x, y, color='r')
plt.show()




回答2:


I am having the same problem. Here is a function which can do it explicitly. Note: It is dropping the points at infinity. There is a lot of space for improvement there; feel free to edit.

def plot_vor_edges(vor, ax=None):

    if ax is None:
        ax = plt.axes()

    ver = vor.vertices

    for reg in vor.regions:
        # Remove vertices at infinity
        if len(reg)>=1:
            if -1 in reg:
                reg = np.roll(reg, -reg.index(-1))
                reg = [x for x in reg if x != -1]

                regionX = ver[reg, 1]
                regionY = ver[reg, 0]
            else:
                regionX = ver[reg + [reg[0]], 1]
                regionY = ver[reg + [reg[0]], 0]

            ax.plot(regionX, regionY, '-k', linewidth=0.5)
        else:
            continue



来源:https://stackoverflow.com/questions/45997002/python-plot-on-top-of-scipy-plot-voronoi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!