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

求助:Voila中Plotly图表单行渲染异常问题排查

Plotly图表在Voila中渲染为单行的修复方案

问题背景

在Jupyter Notebook中使用Plotly绘图并通过Voila生成演示HTML时,图表在Voila中被渲染为单行(显示异常),但在Notebook中显示正常。最小复现代码如下:

import pandas as pd
import ipywidgets as widgets
pd.options.plotting.backend = "plotly"
def draw(b):
    df = pd.DataFrame({'team': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'],
                   'points': [18, 22, 19, 14, 14, 11, 20, 28]})
    with output:
        fig2 = df.plot(kind='line', x='team', y='points')
        fig2.show()
button = widgets.Button(description="Draw")
display(button)
output = widgets.Output()
print("Line above output")
display(output)
print("Line below output")
button.on_click(draw)

解决方法

方法1:替换fig.show()为display(fig)

Voila的渲染机制与Notebook原生环境存在差异,直接调用fig.show()无法正确适配Output部件的布局。改用ipywidgets的display()方法可以让图表正常渲染:

import pandas as pd
import ipywidgets as widgets
pd.options.plotting.backend = "plotly"

def draw(b):
    df = pd.DataFrame({'team': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'],
                   'points': [18, 22, 19, 14, 14, 11, 20, 28]})
    with output:
        output.clear_output(wait=True)  # 可选:每次点击清空历史输出,避免叠加
        fig2 = df.plot(kind='line', x='team', y='points')
        display(fig2)  # 用display替代show()

button = widgets.Button(description="Draw")
display(button)
output = widgets.Output()
print("Line above output")
display(output)
print("Line below output")
button.on_click(draw)

方法2:指定Plotly渲染器

如果坚持使用fig.show(),可以指定渲染器为notebook,强制适配交互式环境的渲染逻辑:

fig2.show(renderer='notebook')

原理说明

Voila运行时不会加载Notebook原生的前端渲染脚本,fig.show()默认的渲染方式无法在Voila的HTML环境中正确解析图表布局。而display(fig)会将Plotly图表转换为ipywidgets兼容的部件,从而在Voila中正常显示完整尺寸的图表。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 15:38:24