【问题标题】:How do you plot on a premade matplotlib plot with IPyWidgets?如何使用 IPyWidgets 在预制的 matplotlib 绘图上绘图?
【发布时间】:2022-11-24 02:05:05
【问题描述】:

我有一个场景,我想在运行小部件之前初始化绘图并在其上绘制一堆东西。但是,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 的值显示在我的绘图中?

谢谢!

【问题讨论】:

    标签: python matplotlib jupyter-lab ipywidgets


    【解决方案1】:

    假设您使用的是 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
    

    【讨论】:

    • 谢谢!另外,有什么方法可以摆脱让您更改视图的一侧的工具栏吗?我只希望能够通过滑块进行交互。
    【解决方案2】:

    你很接近。我已经看到将创建的情节放在您使用交互式包装器调用的函数中。参见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,或者实际上根本没有它,如代码 there 顶部的注释中所述。
    我不想要 %matplotlib widget%matplotlib notebook 制造的额外垃圾和东西使交互性仅限于滑块,就像您似乎也喜欢一样。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-02
      • 2020-11-06
      • 1970-01-01
      • 2019-01-19
      • 2019-05-03
      • 2015-04-24
      相关资源
      最近更新 更多