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

如何在folium地图中添加交互式图表?参考ipyleaflet控件样式

在Folium地图中嵌入交互式图表(非弹窗形式)

Folium本身没有原生提供像ipyleaflet那样的widget控件,但可以通过自定义HTML/JS元素结合branca模块实现类似效果,以下是两个实用示例:

示例1:固定位置的浮动图表面板

在地图右上角添加一个始终可见的交互式Plotly图表:

import folium
from branca.element import Element
import plotly.graph_objects as go
import plotly.io as pio

# 创建基础地图
m = folium.Map(location=[40.7128, -74.0060], zoom_start=10)

# 生成交互式Plotly图表并转为HTML字符串
fig = go.Figure(data=[go.Scatter(x=[1, 2, 3], y=[4, 1, 2])])
chart_html = pio.to_html(fig, full_html=False, include_plotlyjs='cdn')

# 定义带样式的图表面板HTML
panel_html = f"""
<div id="fixed-chart" style="position: absolute; top: 10px; right: 10px; width: 300px; height: 250px; z-index: 9999; background: white; padding: 10px; border-radius: 5px; box-shadow: 0 2px 5px rgba(0,0,0,0.2);">
    {chart_html}
</div>
"""

# 将面板添加到地图
m.get_root().html.add_child(Element(panel_html))

# 保存地图
m.save('fixed_chart_map.html')

示例2:绑定标记的触发式图表

点击地图标记时,在指定位置显示/隐藏交互式图表:

import folium
from branca.element import Element
import plotly.graph_objects as go
import plotly.io as pio

# 创建基础地图
m = folium.Map(location=[40.7128, -74.0060], zoom_start=12)

# 生成柱状图HTML
fig = go.Figure(data=[go.Bar(x=['A', 'B', 'C'], y=[10, 20, 15])])
chart_html = pio.to_html(fig, full_html=False, include_plotlyjs='cdn')

# 添加地图标记
marker = folium.Marker(location=[40.7128, -74.0060])
marker.add_to(m)

# 编写点击标记的交互JS
custom_js = f"""
const marker = document.querySelector('.leaflet-marker-icon[lat="40.7128"][lng="-74.0060"]');
marker.addEventListener('click', function() {{
    let panel = document.getElementById('marker-chart');
    if (!panel) {{
        panel = document.createElement('div');
        panel.id = 'marker-chart';
        panel.style = 'position: absolute; top: 60px; left: 60px; width: 300px; height: 250px; z-index: 9999; background: white; padding: 10px; border-radius: 5px; box-shadow: 0 2px 5px rgba(0,0,0,0.2);';
        panel.innerHTML = `{chart_html}`;
        document.getElementById('map').appendChild(panel);
    }} else {{
        panel.style.display = panel.style.display === 'none' ? 'block' : 'none';
    }}
}});
"""

# 将JS添加到地图
m.get_root().script.add_child(Element(custom_js))

# 保存地图
m.save('marker_triggered_chart.html')

核心要点

  • 可替换Plotly为Bokeh、Highcharts等库,只要能导出HTML字符串即可
  • 通过position: absolute和z-index控制图表在地图层级的显示优先级
  • 若需要图表随地图平移,可监听Leaflet的move事件更新面板位置

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 01:38:26