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

Plotly Choropleth绘制印尼省份人口地图空白问题求助

印尼Choropleth地图空白问题解决指南

问题概述

使用Plotly graph_objects绘制印尼省份人口Choropleth地图时,图例正常显示,但地图区域完全空白。

你的代码

import requests
import pandas as pd
import plotly.graph_objects as go
import streamlit as st  # 补充原代码缺失的st导入

# Load data
df_reshaped = pd.read_csv('D:/Projects/population-dashboard-master/data/id-population-2014-2022-reshaped.csv')

# 补充原代码缺失的year_list定义
year_list = df_reshaped['year'].unique().tolist()

# Sidebar
with st.sidebar:
    st.title('󠁧󠁢󠁥Indonesia Population Dashboard')
    selected_year = st.selectbox('Select a year', year_list)
    df_selected_year = df_reshaped[df_reshaped.year == selected_year]
    color_theme_list = ['blues', 'cividis', 'greens', 'inferno', 'magma', 'plasma', 'reds', 'rainbow', 'turbo', 'viridis']
    selected_color_theme = st.selectbox('Select a color theme', color_theme_list)

# Choropleth map
def make_choropleth(input_df, input_id, input_column, input_color_theme):
    # Get Indonesia geojson data
    geojson = requests.get(
        "https://raw.githubusercontent.com/superpikar/indonesia-geojson/master/indonesia-province-simple.json"
    ).json()

    # Plot choropleth map
    choropleth_map = go.Figure(
        data=go.Choropleth(
            geojson=geojson,
            locations=input_df[input_id],  # Spatial coordinates
            featureidkey="properties.Propinsi",
            z=input_df[input_column],  # Data to be color-coded
            colorscale=input_color_theme,
            colorbar_title=input_id,
        )
    )
    choropleth_map.update_geos(fitbounds="locations", visible=False)

    return choropleth_map

# Calling the function
choropleth = make_choropleth(df_selected_year, 'province', 'population', selected_color_theme)
st.plotly_chart(choropleth, use_container_width=True)

核心原因

地图空白的最常见原因是你的DataFrame中province列的省份名称,与GeoJSON文件中properties.Propinsi字段的名称无法匹配。Plotly无法关联空间数据和属性数据,因此无法渲染地图区域。

解决步骤

1. 排查名称匹配问题

先导出并对比两边的省份名称,找出差异:

# 提取GeoJSON中的所有省份名称
geojson = requests.get("https://raw.githubusercontent.com/superpikar/indonesia-geojson/master/indonesia-province-simple.json").json()
geojson_provinces = [feat['properties']['Propinsi'] for feat in geojson['features']]
print("GeoJSON省份列表:", geojson_provinces)

# 打印你的数据中的省份列表
print("数据中的省份列表:", df_selected_year['province'].unique().tolist())

常见差异包括:大小写不一致、拼写错误、特殊字符(如'或空格)、简称/全称差异(比如“DKI Jakarta” vs “Jakarta”)。

2. 标准化名称格式

对两边的名称做统一处理,消除格式差异:

# 标准化DataFrame中的省份名称:去除空格、转小写
df_selected_year['province'] = df_selected_year['province'].str.strip().str.lower()

# 标准化GeoJSON中的省份名称
for feat in geojson['features']:
    feat['properties']['Propinsi'] = feat['properties']['Propinsi'].strip().lower()

3. 验证数据完整性

检查数据中是否存在缺失值,缺失的province或population会导致对应区域无法渲染:

# 检查缺失值数量
print(df_selected_year[['province', 'population']].isnull().sum())

如果有缺失值,可通过df_selected_year.dropna(subset=['province', 'population'])删除对应行,或补充缺失数据。

4. 优化地图视图设置

如果名称匹配后仍显示异常,可手动设置地图中心和缩放级别,确保印尼区域完整显示:

choropleth_map.update_geos(
    fitbounds="locations",
    visible=False,
    center={"lat": -2.5, "lon": 118.0},  # 印尼地理中心坐标
    projection_scale=4  # 调整缩放比例,数值越大地图越近
)

修正后的完整函数示例

def make_choropleth(input_df, input_id, input_column, input_color_theme):
    geojson = requests.get(
        "https://raw.githubusercontent.com/superpikar/indonesia-geojson/master/indonesia-province-simple.json"
    ).json()

    # 标准化名称,确保匹配
    input_df[input_id] = input_df[input_id].str.strip().str.lower()
    for feat in geojson['features']:
        feat['properties']['Propinsi'] = feat['properties']['Propinsi'].strip().lower()

    choropleth_map = go.Figure(
        data=go.Choropleth(
            geojson=geojson,
            locations=input_df[input_id],
            featureidkey="properties.Propinsi",
            z=input_df[input_column],
            colorscale=input_color_theme,
            colorbar_title="人口数量",  # 更直观的标题
        )
    )
    choropleth_map.update_geos(
        fitbounds="locations",
        visible=False,
        center={"lat": -2.5, "lon": 118.0},
        projection_scale=4
    )

    return choropleth_map

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 07:36:08