【发布时间】:2019-10-21 15:38:59
【问题描述】:
我正在处理Jupyter Notebook,我正在使用以下ipywidget 来设置阈值:
Thr = widgets.IntSlider(value=-17, min=-30, max=-13, step=1, description='Threshold: ', disabled=False, continuous_update=True, orientation='horizontal', readout=True, readout_format='d')
Thr
接下来,我将使用该值屏蔽numpy array:
import numpy.ma as ma
test= ma.masked_less_equal(S_images[0], Thr.value)
最后我绘制了结果:
plt.figure(figsize = (15,15))
plt.imshow(test[0], cmap='gray')
ipywidget 与其他代码位于不同的Jupyter cell 中,因此当我更改Thr 的值时,我必须再次手动运行进行屏蔽和绘图的单元格。
我的问题是:我总是看到那些您更改参数的交互式绘图(在我的例子中是 ipywidget Thr)并自动更新绘图。
我看到widgets.IntSlider 有一个continuous_update 参数,它似乎接近我想要的,但仍然无法获得我想要的行为。
知道这是否可行或可能吗?
_编辑_
从ac24的评论开始,我正在改编他提出的例子:
from IPython.display import display, clear_output
import ipywidgets as ipy
import matplotlib.pyplot as plt
import numpy as np
# setup figure
n = 10
out = ipy.Output()
# show random mesh
def update(idx):
with out:
clear_output()
fig, ax = plt.subplots(figsize = (5,5))
h = ax.imshow(S_images[0]) # here I put my image
h.set_data(np.ma.masked_less_equal(S_images[0], slider.value)) # here I set the task to masked accordint to the `slider.value`
fig.canvas.flush_events()
fig.canvas.draw()
plt.show()
slider = ipy.IntSlider(min = 0, max = 10, orientation = 'vertical')
widget = ipy.interactive(update, idx = slider)
layout = ipy.Layout(
# display = 'flex',
# flex_flow = 'row',
# justify_content = 'space-between',
# align_items = 'center',
)
widgets = ipy.HBox(children=(slider, out), layout = layout)
display(widgets)
这个例子效果很好,正是我想要的。但是,我有一个关于布局的小问题。最初我正在使用 3 张图片,所以我想让它们显示如下,每张图片旁边都有滑块来完成任务:(下面的图片不是真实的,只是为了代表我想要的)
编辑 2
在这种情况下,问题是,一旦我在滑块中选择了一个值,我就会写信给该栅格的 geotiff。为此,我使用以下代码:
with rasterio.open('/Path/20190331_VV_Crop') as src:
ras_meta = src.profile
with rasterio.open('/path/Threshold.tif', 'w', **ras_meta) as dst:
dst.write(X)
但是,我不确定如何在dst.write(X) 中引用 numpy 数组
【问题讨论】:
-
在另一个问题(stackoverflow.com/questions/58556700/…)中有一个简单的例子。它应该提供交互功能的基础知识以及如何显示图表。
continuous_update参数提供了一些不同的功能,在我的示例中进行试验,看看你是否能弄清楚它是如何工作的。 -
@ac24 非常感谢您的评论。如果您将其添加为答案,我将很乐意接受。我只是对布局有一点意见。我已经编辑了我的问题以添加问题。你能评论一下吗?
标签: python matplotlib jupyter-notebook ipywidgets