You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jupyter中如何并排展示Plotly交互式图表与Markdown文本并控制宽高

实现方案

1. 控制左右组件宽度

你使用的是ipywidgets的flex布局容器,直接给两个子组件分别指定宽度即可:

  • 左侧Plotly FigureWidget 设宽度为60%
  • 右侧Markdown对应的HTML组件设宽度为40%

2. 控制图表高度

直接在Plotly的布局配置中添加height参数即可自定义图表高度,也可以同步给容器组件设置高度避免内容溢出。

修改后可直接运行的完整代码

from ipywidgets import widgets, Layout
from IPython.display import display, 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
)

# 控制图表高度 此处设置为500px,可按需调整
figSubs.update_layout(
    margin=go.layout.Margin(l=20,t=10,b=10,pad=4),
    height=500
)
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""")

# 分别给两个子组件设置宽度
left_layout = Layout(width='60%')
right_layout = Layout(width='40%')
# 给子组件挂载对应布局
fig_component = widgets.Box([figSubs], layout=left_layout)
md_component = widgets.Box([widgets.HTML(mdout._repr_markdown_())], layout=right_layout)

box_layout = Layout(display='flex',
                    flex_flow='row',
                    justify_content='space-around',
                    width='100%'
                   )
hbox1 = widgets.Box(children=[fig_component, md_component], layout=box_layout)
display(hbox1)

可选:修复Markdown解析问题

如果需要正确渲染Markdown格式,可以安装markdown库后手动转译:

# 先安装依赖:pip install markdown
import markdown
html_content = markdown.markdown(f"""There are {len_x} **elements** of both `the_x`, and `the_y`;

Those values are plotted on the diagram on the left""")
md_component = widgets.Box([widgets.HTML(html_content)], layout=right_layout)

内容的提问来源于stack exchange,提问作者sdbbs

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 01:06:03