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

标签 python matplotlib figure

是否可以在 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()

关于python - 与python的matplotlib图交互: assign value to selected features,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33231120/

相关文章:

Python Numpy 2D绘图设置具有自动缩放功能的y-tics总数

python - Matplotlib ArtistAnimation 一步显示多个元素

plot - 多曲面图包括 Plotly 中的布局?

python - 在Python中水平合并具有不同分隔符和列的CSV的最快方法?

python import 执行本地文件

python - Pandas :获取所有具有常量值的列

python - 分配一个既设置又返回值的方法的未使用的返回值?

r - 具有置信区间的箱线图并识别 r 中的特定数据点

latex - 两列 Latex 文档中带有一个标题的几个图形

python - 如何在 python 中读取 9 兆字节 block 中的文件?