与 python 的 matplotlib 图交互:为所选特征赋值

Interaction with python's matplotlib figure: assign value to selected features

是否可以 select matplotlib 图形内的一个区域 window 分配值,比如 0?例如,假设我想编写一个脚本,在某个时刻,在图形 window (pyplot.imshow) 中显示图像,并要求用户 select 一个区域赋值0? 希望已经足够清楚了。

这很好用。这里有一个 pcolormesh,您可以在其中单击,捕获单击事件的 onclick 函数将处理它并将选定的方块设置为零。 mpl_connect 函数将 onclick 函数连接到 button_press_event 事件。点击后可以直接看到更新

import numpy as np
import pylab as pl

pl.ioff()

rand_field = np.random.rand(10,10)

fig = pl.figure()
cm = pl.pcolormesh(rand_field, vmin=0, vmax=1)
pl.colorbar()

def onclick(event):
    indexx = int(event.xdata)
    indexy = int(event.ydata)
    print("Index ({0},{1}) will be set to zero".format(indexx, indexy))
    rand_field[indexy, indexx] = 0.
    cm.set_array(rand_field.ravel())
    event.canvas.draw()

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

pl.show()

在这里您可以找到一个更高级的版本,它可以拖动一个区域并处理错误,以防有人在图外单击。我把矩形的绘图留给你:

import numpy as np
import pylab as pl

pl.ioff()

rand_field = np.random.rand(10,10)

fig = pl.figure()
cm = pl.pcolormesh(rand_field, vmin=0, vmax=1)
pl.colorbar()

x_press = None
y_press = None

def onpress(event):
    global x_press, y_press
    x_press = int(event.xdata) if (event.xdata != None) else None
    y_press = int(event.ydata) if (event.ydata != None) else None

def onrelease(event):
    global x_press, y_press
    x_release = int(event.xdata) if (event.xdata != None) else None
    y_release = int(event.ydata) if (event.ydata != None) else None

    if (x_press != None and y_press != None and x_release != None and y_release != None):
        (xs, xe) = (x_press, x_release+1) if (x_press <= x_release) else (x_release, x_press+1)
        (ys, ye) = (y_press, y_release+1) if (y_press <= y_release) else (y_release, y_press+1)
        print("Slice [{0}:{1},{2}:{3}] will be set to zero".format(xs, xe, ys, ye))
        rand_field[ys:ye, xs:xe] = 0.
        cm.set_array(rand_field.ravel())
        event.canvas.draw()

    x_press = None
    y_press = None

cid_press   = fig.canvas.mpl_connect('button_press_event'  , onpress  )
cid_release = fig.canvas.mpl_connect('button_release_event', onrelease)

pl.show()