Control of layout ipywidgets in jupyter notebook

本秂侑毒 提交于 2019-12-08 14:19:56

问题


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.

The problem

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)

However it results in

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


回答1:


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)



来源:https://stackoverflow.com/questions/58556700/control-of-layout-ipywidgets-in-jupyter-notebook

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!