如何使用IPyWidgets在预先制作的matplotlib图上绘图?

yebdmbv4  于 2022-11-24  发布在  其他
关注(0)|答案(2)|浏览(140)

我有一个场景,我想初始化绘图并在运行小部件之前在上面绘制一堆东西。但是,jupyter小部件拒绝在我已经绘制好的绘图上绘制。相反,什么也没有显示。下面是一个简化的例子。

import matplotlib.pyplot as plt
import ipywidgets as widgets
from IPython import display 

fig=plt.figure(1,(2,2))
axs=fig.gca()

def testAnimate(x):
    axs.text(0.5,0.5,x)

xs=widgets.IntSlider(min=0,max=3,value=1) #Create our intslider such that the range is [1,50] and default is 10

gui = widgets.interactive(testAnimate, x=xs) #Create our interactive graphic with the slider as the argument
display.display(gui)    #display it

我希望x的值能在axs上显示出来,但事实并非如此。我意识到,在这种情况下,我可以只做plt.text,但在我的实际项目中,这是不可行的。那么,我如何让x的值显示在我的绘图上呢?
谢谢你!

u3r8eeie

u3r8eeie1#

假设你正在使用Jupyter Notebook,你首先必须初始化交互式matplotlib。你可以通过运行以下任意一个魔术命令来完成这个任务:

  • %matplotlib notebook
  • %matplotlib widget。此版本需要安装ipympl

然后,执行:

import matplotlib.pyplot as plt
import ipywidgets as widgets
from IPython import display 

fig, ax = plt.subplots()
text = ax.text(0.5, 0.5, "0")

def testAnimate(x):
    text.set_text(x)

xs=widgets.IntSlider(min=0,max=3,value=1) #Create our intslider such that the range is [1,50] and default is 10

gui = widgets.interactive(testAnimate, x=xs) #Create our interactive graphic with the slider as the argument
display.display(gui)    #display it
egmofgnx

egmofgnx2#

你已经接近了。我已经看到了把情节创建在你用交互式 Package 器调用的函数中。见here
通过移动函数中的两行将其转换为代码,您的笔记本单元格将为:

import matplotlib.pyplot as plt
import ipywidgets as widgets
from IPython import display 

def testAnimate(x):
    fig=plt.figure(1,(2,2))
    axs=fig.gca()
    axs.text(0.5,0.5,x)

xs=widgets.IntSlider(min=0,max=3,value=1) #Create our intslider such that the range is [1,50] and default is 10

gui = widgets.interactive(testAnimate, x=xs) #Create our interactive graphic with the slider as the argument
gui

请注意,这可以在%matplolib inline的情况下工作,或者实际上根本不需要%matplolib inline,如代码there顶部的注解所述。
我不想要%matplotlib widget%matplotlib notebook制造的额外的cruft和东西,使交互性限于滑块,就像你似乎也喜欢。
而且由于ipywidgets的交互能力会使widgets自动化,你可以进一步简化为:

import matplotlib.pyplot as plt
import ipywidgets as widgets
from IPython import display 

def testAnimate(x):
    fig=plt.figure(1,(2,2))
    axs=fig.gca()
    axs.text(0.5,0.5,x)

gui = widgets.interactive(testAnimate, x=(0,3,1))
gui

相关问题