Skip to main content
 首页 » 编程设计

python之与python的matplotlib交互图: assign value to selected features

2024年10月24日14itcoder

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

请您参考如下方法:

这很好用。这里有一个 pcolormesh,您可以在其中单击,捕获单击事件的 onclick 函数将处理它并将选定的方 block 设置为零。 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()