在Jupyter Notebook中控制布局ipywidgets [英] Control of layout ipywidgets in jupyter notebook

查看:186
本文介绍了在Jupyter Notebook中控制布局ipywidgets的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在理解如何控制jupyter笔记本中的ipywidget的flexbox时遇到一些问题.根据 docs ,这应该可行,但是我的样式代码(请参见下文)无法产生所需的布局.我检查了一下堆栈,发现了一个良好的资源,似乎对那里的人有用,但是运行代码仍然无法提供理想的结果.

I have some problems understanding how to control the flexbox of ipywidgets in jupyter notebook. According to the docs this should be possible, however my styling code (see below) does not result in the desired layout. I checked on stack and found a good resource that seemed to work for people there, however running the code still does not provide the desired the result.

我希望控件构建更复杂的布局.在这种情况下,特别的目标是使滑块垂直于matpltolib图的旁边:

I would like control to build somewhat more complex layouts. In this case particularly the goal is to have the sliders vertically next to the matpltolib plot:

from matplotlib.pyplot import subplots
from IPython.display import display
import ipywidgets as ipy
import numpy as np

# setup figure
n = 10
fig, ax = subplots(figsize = (5,5))
h = ax.imshow(np.random.rand(n, n))

# show random mesh
def update(idx):
    h.set_data(np.random.rand(n, n))
    fig.canvas.flush_events()
    fig.canvas.draw()
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(widget.children[::-1], layout = layout)
display(widgets)

但是它会导致

如何使用jupyter笔记本中的ipywidget强制将布局设置为水平列?

How can I force the layout to be horizontal columns using ipywidgets in jupyter notebook?

推荐答案

尝试专门创建一个包含窗口小部件的输出小部件,然后将其作为孩子的一个放置在HBox中:

Try specifically creating an output widget to contain your chart, and then placing that as one of your children in a HBox:

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(np.random.rand(n, n))
        h.set_data(np.random.rand(n, n))
        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)

这篇关于在Jupyter Notebook中控制布局ipywidgets的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆