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

为何Plotly离线图表无法嵌入Dominate生成的HTML页面?

问题描述

使用plotly.express创建地图,通过dominate库生成HTML页面。单独生成的地图HTML可以正常显示,但将地图代码嵌入dominate生成的页面时,地图仅存在于HTML源码中,无法在浏览器里渲染显示。

相关代码示例:

import dominate
from dominate.tags import *
from dominate.util import raw
import plotly.express as px
import plotly.offline as pyo
import pandas as pd

# 获取包含Latitude、Longitude、ImageNo字段的数据集
can_whole_df=get_some_df()

fig = px.scatter_mapbox(can_whole_df, lat="Latitude", lon="Longitude",
                            zoom=10,
                            text = 'ImageNo'
                        )
fig.update_layout(mapbox_style="open-street-map", margin={"r":0,"t":0,"l":0,"b":0})

fig.write_html("debugmap.html")  # 此步骤正常生成可显示的地图页面

# 尝试将地图嵌入dominate页面
the_map= pyo.plot(fig, include_plotlyjs=False, output_type='div')

doc=dominate.document(title="some map")
with doc.head:
    link(rel='stylesheet', href='style.css')

with doc:
    h1("The Map in all its glory!")
    raw(the_map)
print(doc)
问题原因与解决办法

问题出在pyo.plot的include_plotlyjs=False参数:这个设置会让生成的div代码不包含Plotly的JavaScript库依赖,但浏览器渲染Plotly地图必须依赖这个JS库才能正常工作。单独用fig.write_html能正常显示,是因为这个方法默认会自动引入Plotly JS。

有两种修复方式:

方式一:生成div时引入CDN版Plotly JS

修改pyo.plot的参数,把include_plotlyjs设为'cdn',这样生成的div会自动添加CDN链接加载Plotly JS:

the_map= pyo.plot(fig, include_plotlyjs='cdn', output_type='div')

方式二:手动在dominate的head中添加Plotly JS链接

保持include_plotlyjs=False,但在dominate的head标签里手动引入Plotly的CDN JS:

doc=dominate.document(title="some map")
with doc.head:
    link(rel='stylesheet', href='style.css')
    # 添加Plotly JS的CDN链接
    script(src="https://cdn.plot.ly/plotly-latest.min.js")

with doc:
    h1("The Map in all its glory!")
    raw(the_map)

两种方式任选其一,都能让浏览器加载到Plotly JS,从而正常渲染地图。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 20:40:26