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

使用Plotly绘制印度区级Choropleth地图失败,寻求解决办法

印度区级Choropleth地图Plotly绘制问题及解决方法

问题背景

已成功使用Plotly绘制印度邦级Choropleth地图,但使用本地GeoJSON文件绘制区级地图时Plotly代码失效,不过Matplotlib结合GeoPandas可正常绘制局部地图。

数据集

df = {
    'district': ['Thiruvananthapuram', 'Kasaragod', 'Malappuram', 'Pathanamthitta', 'Wayanad', 'Alappuzha', 'Kozhikode',
                 'Kollam', 'Thrissur', 'Palakkad', 'Kannur', 'Kottayam', 'Ernakulam', 'Idukki'],
    'registeredUsers': [989791, 294943, 871127, 271165, 234308, 534116, 887215, 623472, 768604, 620428, 640842, 504349,
                        1454447, 277492],
    'appOpens': [5574116, 5220451, 9688261, 4036616, 6349929, 2971951, 8824744, 4995465, 5764628, 9057055, 8394165,
                 4454903, 8812130, 9903479]
}

可用的邦级Plotly代码

fig = px.choropleth(
    df,
    geojson="https://gist.githubusercontent.com/jbrobst/56c13bbbf9d97d187fea01ca62ea5112/raw/e388c4cae20aa53cb5090210a42ebb9b765c0a36/india_states.geojson",
    featureidkey='properties.ST_NM',
    locations='state',
    color='registeredUsers',
    color_continuous_scale="viridis_r"
    #scope="asia",
    #range_color = (0, 12),
    #color_continuous_scale='Blues'
)

fig.update_geos(fitbounds="locations", visible=False)
fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0}) #scale map
fig.show()

失效的区级Plotly代码

fig = px.choropleth(
    df,
    geojson="/Users/adityaradhakrishnan/Desktop/output.geojson",
    featureidkey='properties.dtname',
    locations='district',
    color='registeredUsers',
    color_continuous_scale="viridis_r"
    #scope="asia",
    #range_color = (0, 12),
    #color_continuous_scale='Blues'
)

fig.update_geos(fitbounds="locations", visible=False)
fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0}) #scale map
fig.show()

可用的Matplotlib+GeoPandas代码

import matplotlib.pyplot as plt
import geopandas as gpd

# Read GeoJSON data into a GeoDataFrame
gdf = gpd.read_file("/Users/adityaradhakrishnan/Desktop/output.geojson")

# Merge the GeoDataFrame with your DataFrame based on the 'district' column
merged = gdf.merge(df, left_on='dtname', right_on='district')

# Plot the choropleth map
fig, ax = plt.subplots(figsize=(10, 8))
merged.plot(column='registeredUsers', cmap='viridis_r', linewidth=0.8, ax=ax, edgecolor='0.8', legend=True)

# Set plot title and axis labels
ax.set_title('Registered Users by District')
ax.set_xlabel('Longitude')
ax.set_ylabel('Latitude')

# Show the plot
plt.show()

解决方法

1. 校验GeoJSON路径与字段匹配

  • 确保本地GeoJSON绝对路径正确,或把文件放在代码同目录下简化路径;
  • 用GeoPandas读取GeoJSON后,输出gdf[['dtname']].head(),确认properties.dtname字段存在,且与数据集district列的名称完全一致(注意大小写、空格、拼写差异)。

2. 统一名称格式

若存在名称不一致问题,预处理数据和GeoJSON字段:

import pandas as pd
import geopandas as gpd

# 转换数据集为DataFrame并标准化名称
df_pd = pd.DataFrame(df)
df_pd['district'] = df_pd['district'].str.lower().str.strip()

# 读取并标准化GeoJSON的区县名称
gdf = gpd.read_file("/Users/adityaradhakrishnan/Desktop/output.geojson")
gdf['dtname'] = gdf['dtname'].str.lower().str.strip()

# 保存处理后的GeoJSON(后续可直接使用)
gdf.to_file("cleaned_districts.geojson", driver='GeoJSON')

3. 调整Plotly地理范围设置

区级GeoJSON范围较小,可手动设置地图中心和缩放级别:

fig = px.choropleth(
    df_pd,
    geojson="cleaned_districts.geojson",
    featureidkey='properties.dtname',
    locations='district',
    color='registeredUsers',
    color_continuous_scale="viridis_r"
)

# 针对喀拉拉邦设置中心经纬度和缩放级别
fig.update_geos(
    fitbounds="locations",
    visible=False,
    center=dict(lat=10.8505, lon=76.2711),
    zoom=7
)
fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0})
fig.show()

4. 升级Plotly版本

旧版本可能存在本地GeoJSON支持bug,执行升级命令:

pip install --upgrade plotly

5. 调试匹配情况

添加代码检查数据与GeoJSON的匹配度:

geo_districts = set(gdf['dtname'])
data_districts = set(df_pd['district'])

print("匹配的区县:", geo_districts & data_districts)
print("数据集中未匹配的区县:", data_districts - geo_districts)
print("GeoJSON中未匹配的区县:", geo_districts - data_districts)

根据结果修正名称不匹配的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 10:00:02