在 Jupyter 中并排显示交互式绘图和 Markdown 文本

Show interactive plot and Markdown text, side-by-side, in Jupyter

我想在 Jupyter 中并排显示绘图和一些 Markdown 文本(将显示 Python 变量值)。我想出了这个例子,它使用 Plotly 进行绘图:

from ipywidgets import widgets, Layout
from IPython.display import display, Javascript, Markdown as md
import numpy as np
import plotly.graph_objs as go
from plotly.subplots import make_subplots

def func(x, a, b, c, d):
  return a + b*np.exp(c*x + d)

the_x = np.arange(0, 10, 0.5)
the_y = func(the_x, 1, 1, -1, 2)

figSubs = go.FigureWidget(
    make_subplots(rows=1, cols=1, specs = [[{}]], vertical_spacing = 0.05)
)
figSubs.add_trace(
    go.Scatter(mode='markers', x=the_x, y=the_y, name='my function', marker={'color': 'green'}),
    row=1, col=1
)

figSubs.update_layout(margin=go.layout.Margin(l=20,t=10,b=10,pad=4))
figSubs.update_yaxes(zeroline=True,showline=True,zerolinewidth=1,zerolinecolor="#000", row=1, col=1)

len_x = len(the_x)

mdout = md(f"""There are {len_x} **elements** of both `the_x`, and `the_y`;

Those values are plotted on the diagram on the left""")


box_layout = Layout(display='flex',
                    flex_flow='row',
                    justify_content='space-around',
                    width='auto'
                   )
hbox1 = widgets.Box(children=[figSubs, widgets.HTML(mdout._repr_markdown_())], layout=box_layout)
display(hbox1)

这通常有效:

... 除了我看不到:

有谁知道我如何让它工作?

(编辑:刚刚注意到降价实际上并没有像我想要的那样解析为 HTML,但这是另一个问题)

你必须将 auto_size 设置为 False。这可以通过调用 plotly 中的 update_layout 来关闭。然后将 heightwidth 设置为布局。

使用以下解决方案重新创建和生成代码:

from ipywidgets import widgets, Layout
from IPython.display import display, Javascript, Markdown as md
import numpy as np
import plotly.graph_objs as go
from plotly.subplots import make_subplots


def func(x, a, b, c, d):
    return a + b * np.exp(c * x + d)


the_x = np.arange(0, 10, 0.5)
the_y = func(the_x, 1, 1, -1, 2)

figSubs = go.FigureWidget(make_subplots(rows=1, cols=1, specs=[[{}]], vertical_spacing=0.05))
figSubs.add_trace(
    go.Scatter(mode="markers", x=the_x, y=the_y, name="my function", marker={"color": "green"}), row=1, col=1
)

figSubs.update_layout(margin=go.layout.Margin(l=20, t=10, b=10, pad=4))
figSubs.update_yaxes(zeroline=True, showline=True, zerolinewidth=1, zerolinecolor="#000", row=1, col=1)

len_x = len(the_x)

mdout = md(
    f"""There are {len_x} **elements** of both `the_x`, and `the_y`;

Those values are plotted on the diagram on the left"""
)


box_layout = Layout(display="flex", flex_flow="row", justify_content="space-around", width="auto")

figSubs.update_layout(
    autosize=False, width=1000, height=300,
)
hbox1 = widgets.Box(children=[figSubs, widgets.HTML(mdout._repr_markdown_())], layout=box_layout)
display(hbox1)