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

如何在Jupyter Notebook导出的HTML中保留mapbox_layers图层

解决Plotly导出HTML时mapbox_layers丢失的问题

问题原因

Jupyter Notebook默认的HTML导出功能仅捕获图表的静态渲染结果,未完整序列化Plotly图表中mapbox_layers的交互配置;部分Plotly导出方式若参数配置不当,也会遗漏mapbox_layers的定义。

解决方案

1. 使用Plotly官方API直接导出HTML

放弃Jupyter自带的“导出为HTML”功能,改用Plotly的plotly.io.write_html()或plotly.offline.plot()方法,确保完整保存所有图层配置。

示例代码:

import plotly.express as px
import plotly.io as pio
import json

# 加载示例数据与基础GeoJSON
df = px.data.election()
base_geojson = px.data.election_geojson()

# 创建基础choropleth_mapbox图表
fig = px.choropleth_mapbox(
    df,
    geojson=base_geojson,
    color="Bergeron",
    locations="district",
    featureidkey="properties.district",
    mapbox_style="carto-positron",
    zoom=9,
    center={"lat": 45.5517, "lon": -73.7073},
    opacity=0.5
)

# 添加自定义mapbox_layers(加载本地GeoJSON并转为字典)
with open("custom_boundaries.geojson") as f:
    custom_layer_geo = json.load(f)

fig.update_layout(
    mapbox_layers=[
        {
            "source": custom_layer_geo,
            "type": "line",
            "color": "red",
            "line": {"width": 2},
            "below": "traces"
        }
    ]
)

# 导出完整HTML,包含所有图层
pio.write_html(fig, "complete_map.html", include_plotlyjs="cdn")
# 也可使用离线plot方法
# from plotly.offline import plot
# plot(fig, filename="complete_map.html")

2. 确保mapbox_layers的source配置正确

  • 若图层使用本地GeoJSON文件,必须先加载为Python字典对象再传入source,不能直接使用本地文件路径(导出后的HTML无法访问本地路径资源)。
  • 若使用在线GeoJSON资源,确保URL可公开访问,导出后HTML能正常加载。

3. 配置PlotlyJS资源打包方式

  • include_plotlyjs="cdn":依赖在线CDN加载PlotlyJS,文件体积小,但需联网才能正常显示。
  • include_plotlyjs="inline":将PlotlyJS代码内嵌到HTML中,文件体积大,但可离线打开。
  • include_plotlyjs="directory":将PlotlyJS资源保存到本地目录,适合离线部署。

验证方法

导出后直接打开生成的HTML文件,检查mapbox_layers是否正常显示;若仍有问题,可打开HTML源码,搜索mapbox_layers关键字,确认配置是否被正确写入。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 10:15:07