在Jupyter Notebook中滑块值变化时更新多个图表

0 投票
2 回答
36 浏览
提问于 2025-04-14 15:20

我想在jupyter notebook中,当IntSlider的值改变时,更新多个imshow图像。但是我的代码有什么问题呢?

这是我使用的版本

import ipywidgets as widgets
import matplotlib.pyplot as plt
import matplotlib
import numpy as np

print( 'versions: ipywidgets = ', widgets.__version__)
print( '          matplotlib = ', matplotlib.__version__)
print( '          numpy      = ', np.__version__)

这是相应的输出结果

versions: ipywidgets =  8.0.4
          matplotlib =  3.5.0
          numpy      =  1.20.3

这是代码

def plot_image(ax, seed=0):
    np.random.seed(0)
    data2plot = np.random.rand(5,5)
    img = ax.imshow(data2plot)

fig = plt.figure( figsize=(12,6) )
ax1 = fig.add_subplot(1,2,1)
ax2 = fig.add_subplot(1,2,2)

plot_image(ax1)
plot_image(ax2)

plt.show()

slider = widgets.IntSlider(value=0, min=0, max=100, step=1)

# callback function for the slider widget
def update(change):
    plot_image(ax1, seed=0)
    plot_image(ax2, seed=change.new)
    fig.canvas.draw()

# connect update function to slider widget using the .observe() method, observing changes in value attribute
slider.observe(update 'value')
slider

这里有一个滑块,见截图,我可以改变它的值,但没有任何效果。我漏掉了什么呢?

截图

2 个回答

1

我想问题出在函数 plot_image 里面根本没有用到 seed 这个值。这个函数的第一行应该改成 np.random.seed(seed),而不是 np.random.seed(0)。这样一来,当你移动滑块的时候,第二个子图就会更新(第一个面板会保持不变,因为种子是0,不管滑块的值是什么)。

2

把你的代码和Markus的建议结合起来,同时解决你实现中的另外两个问题,这样应该就能正常工作了:

%matplotlib ipympl
import ipywidgets as widgets
import matplotlib.pyplot as plt
import matplotlib
import numpy as np

def plot_image(ax, seed=0):
    np.random.seed(seed)
    data2plot = np.random.rand(5,5)
    img = ax.imshow(data2plot)

fig = plt.figure( figsize=(12,6) )
ax1 = fig.add_subplot(1,2,1)
ax2 = fig.add_subplot(1,2,2)

plot_image(ax1)
plot_image(ax2)

plt.show()

slider = widgets.IntSlider(value=0, min=0, max=100, step=1)

# callback function for the slider widget
def update(change):
    plot_image(ax1, seed=0)
    plot_image(ax2, seed=change.new)
    fig.canvas.draw()

# connect update function to slider widget using the .observe() method, observing changes in value attribute
slider.observe(update, 'value')
slider

具体细节:

撰写回答