如何将用户在Matplotlib中输入的点传递给np.array?

时间:2017-07-13 12:36:55

标签: python numpy matplotlib scipy voronoi

我想创建一个程序,允许用户首先在Matplotlib图中输入点,然后使用这些点创建Voronoi图。

找出2个部分,但不是连接。如何传递用户输入的点并在Voronoi部分中使用它? (我只需要知道如何将points = np.random.rand(20,2)更改为用户输入的点数。)

绘制点数:

import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_xlim([0, 10])
ax.set_ylim([0, 10])

def onclick(event):
    print('x=%d, y=%d, xdata=%f, ydata=%f' %
          (event.x, event.y, event.xdata, event.ydata))
    plt.plot(event.xdata, event.ydata, 'bo')
    fig.canvas.draw()

cid = fig.canvas.mpl_connect('button_press_event', onclick)
plt.show()`

创建Voronoi图:

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

fig = plt.figure()

points = np.random.rand(20,2)

vor = Voronoi(points)

voronoi_plot_2d(vor)

plt.show()

2 个答案:

答案 0 :(得分:2)

您可以使用类来存储点,然后在同一图中绘制图表。在下面的示例中,您将使用鼠标左键放置点,并使用鼠标右键绘制voronoi图。如果您以后想要在图中添加新点,则可以这样做。

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

fig, ax  = plt.subplots()
ax.set_xlim([0, 10])
ax.set_ylim([0, 10])

class V():
    def __init__(self, ax = None):
        self.ax = ax
        if not self.ax: self.ax = plt.gca()
        tx = "left click to place points\nright click to plot voronoi diagram"
        self.text = self.ax.text(0.1,0.9, tx, transform=self.ax.transAxes, 
                                 ha="left", va="top")
        self.cid = fig.canvas.mpl_connect('button_press_event', self.onclick)
        self.points = []

    def onclick(self, event):
        self.text.set_visible(False)
        if event.button == 1:
            print('x=%d, y=%d, xdata=%f, ydata=%f' %
                  (event.x, event.y, event.xdata, event.ydata))
            plt.plot(event.xdata, event.ydata, 'bo')
            self.points.append((event.xdata, event.ydata))
        else:
            self.voronoi()
        fig.canvas.draw()

    def voronoi(self):
        self.ax.clear()
        vor = Voronoi(self.points)
        voronoi_plot_2d(vor, ax=self.ax)


v = V(ax=ax)
plt.show()

enter image description here

答案 1 :(得分:1)

您可以将x-y对保存在列表中,然后将其转换为数组:

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


fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_xlim([0, 10])
ax.set_ylim([0, 10])


points = []
def onclick(event):
    print('x=%d, y=%d, xdata=%f, ydata=%f' %
          (event.x, event.y, event.xdata, event.ydata))
    points.append([event.xdata,event.ydata])
    plt.plot(event.xdata, event.ydata, 'bo')
    fig.canvas.draw()

cid = fig.canvas.mpl_connect('button_press_event', onclick)
plt.show()

fig2 = plt.figure()

vor = Voronoi(np.array(points))

voronoi_plot_2d(vor)

plt.show()

只要用户点击图中,就会将点添加到列表中,直到用户关闭原始图。之后,创建一个新图形并绘制Voronoi图。希望这会有所帮助。