如何为Plotly Density Mapbox密度地图添加美国县界边界图层
解决方案
你只需要在mapbox_layers配置项中新增一个矢量图层加载美国县界的GeoJSON数据即可,完整可运行代码如下:
import plotly.express as px import pandas as pd import json # 示例数据 df = pd.DataFrame(data=([[32.4087249155, -100.9509696428, '2013-01-01', 1], [31.5201976084, -102.1030942593, '2013-01-01', 1], [31.434573418, -102.0592907601, '2013-01-01', 1], [31.2635930582, -101.95341361, '2013-01-01', 1], [31.4287233847, -102.0253840388, '2013-01-01', 1], [31.4872286706, -101.5455598032, '2021-01-01', 1], [31.5439162579, -101.4833865708, '2021-01-01', 1], [31.5439362581, -101.4833065695, '2021-01-01', 1], [31.7980713977, -102.0937650441, '2021-01-01', 1], [32.02050082, -103.31736372, '2021-01-01', 1]]), columns=['Latitude', 'Longitude', 'Date', 'Count']) # 读取本地存储的美国县界GeoJSON文件,该公开数据可从美国人口普查局官方渠道获取 with open('us_counties.geojson', 'r', encoding='utf-8') as f: us_counties_geojson = json.load(f) fig = px.density_mapbox(df, lat='Latitude', lon='Longitude', z='Count', radius=10, zoom=3, height=700, animation_frame='Date', ) fig.update_layout( mapbox_layers=[ # 原有USGS卫星底图层 { "below": 'traces', "sourcetype": "raster", "sourceattribution": "United States Geological Survey", "source": [ "https://basemap.nationalmap.gov/arcgis/rest/services/USGSImageryOnly/MapServer/tile/{z}/{y}/{x}" ] }, # 新增美国县界图层 { "below": 'traces', "sourcetype": "geojson", "source": us_counties_geojson, "type": "line", "color": "#888888", "line": {"width": 0.8} } ], mapbox_style = "white-bg" ) fig.show()
参数调整说明
- 若希望县界显示在密度热图上方,删除新增图层的
"below": 'traces'配置即可 - 可通过修改
color和line.width参数调整边界的颜色和粗细,适配不同底图风格
内容的提问来源于stack exchange,提问作者tchanque
相关产品推荐
相关产品推荐

