问题
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