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

如何为Streamlit中的Folium地图添加离散颜色图例

为Streamlit中的Folium离散分类地图添加图例

你可以通过自定义HTML图例的方式,直接将分类与对应颜色、风速区间展示在地图上,以下是修改后的完整代码:

import streamlit as st
import folium
from streamlit_folium import st_folium
import pandas as pd

from folium.plugins import MarkerCluster
from services.utils import load_data, get_mid

df = load_data('./data/data.csv')

col1, col2, col3 = st.columns(3)

with col1:
    RCP = st.selectbox('RCP', ("Baseline", "4.5", "8.5"))

with col2:
    RP = st.selectbox('RP', ("1000", "500", "100", "50", "20", "10"))

with col3:
    Year = st.selectbox("Year", ("2050", "2080"))

if RCP == "Baseline":
    RCP = "45"
elif RCP == "4.5":
    RCP = "45"
else:
    RCP = "85"

if Year == "2050":
    Year = "2041-2060"
else:
    Year = "2081-2100"

# SPD_tc_1000_ARI_RCP85_2041-2060
column_string = f"SPD_tc_{RP}_ARI_RCP{RCP}_{Year}"

df_viz = pd.concat(
    [df['Address'], df['Latitude'], df['Longitude'], df[column_string]], axis=1)

mean_latitude, mean_longitude = get_mid(df_viz)
m = folium.Map(location=[mean_latitude, mean_longitude], zoom_start=5)

color_scale = {
    'Category - 1': 'green',
    'Category - 2': 'yellow',
    'Category - 3': 'orange',
    'Category - 4': 'red',
    'Category - 5': 'purple'
}

# 定义分类对应的风速区间,用于图例展示
category_info = [
    ("Category - 1: ≤55.21", "green"),
    ("Category - 2: 55.65-64.29", "yellow"),
    ("Category - 3: 64.50-75.76", "orange"),
    ("Category - 4: 75.90-90.56", "red"),
    ("Category - 5: ≥91.07", "purple")
]

# 创建自定义HTML图例
legend_html = '''
<div style="position: fixed; 
            bottom: 50px; right: 50px; width: 180px; height: auto; 
            background-color: white; z-index:9999; font-size:14px;
            border:2px solid grey; padding: 10px;">
    <b>Wind Speed Category</b><br>
'''
for name, color in category_info:
    legend_html += f'    <i style="background:{color}; width:15px; height:15px; display:inline-block; margin-right:8px;"></i>{name}<br>'
legend_html += '</div>'

# 将图例添加到地图
m.get_root().html.add_child(folium.Element(legend_html))

marker_cluster = MarkerCluster().add_to(m)

for index, row in df_viz.iterrows():
    category = None
    if row[column_string] <= 55.21:
        category = 'Category - 1'
    elif 55.65 <= row[column_string] <= 64.29:
        category = 'Category - 2'
    elif 64.50 <= row[column_string] <= 75.76:
        category = 'Category - 3'
    elif 75.90 <= row[column_string] <= 90.56:
        category = 'Category - 4'
    elif row[column_string] >= 91.07:
        category = 'Category - 5'

    if category:
        folium.CircleMarker(
            location=[row['Latitude'], row['Longitude']],
            stroke=False,
            radius=10,
            color=color_scale[category],
            fill=True,
            fill_color=color_scale[category],
            fill_opacity=0.7,
            popup=folium.Popup(
                f"Wind Speed: {round(row[column_string], 2)}", max_width=300)
        ).add_to(m)


folium.plugins.Draw(export=True).add_to(m)
output = st_folium(m, width=700, height=500)
st.write(df_viz)

关键说明:

  1. 分类信息定义:创建category_info列表,把每个分类的名称、对应颜色和风速区间绑定,让图例信息更直观。
  2. 自定义HTML图例:通过HTML代码构建固定在地图右下角的图例框,设置白色背景、灰色边框和高层级(z-index)确保不会被地图元素遮挡。
  3. 添加到地图:使用m.get_root().html.add_child()将HTML图例元素注入到Folium地图中,完成图例的渲染。

你可以根据需求调整图例的位置(修改bottom/right参数)、宽度、字体大小等样式属性,适配你的页面布局。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 03:44:54