如何在Dash Plotly的choropleth_mapbox标签中设置垂直文本?
实现Choropleth Mapbox标签垂直旋转并沿图形排布的方案

核心实现方法
要让Mapbox choropleth的标签垂直旋转并贴合图形边缘,需通过自定义Mapbox图层控制文本旋转逻辑,以下分两种场景给出具体实现:
场景1:统一设置垂直标签
如果只需要所有标签统一垂直显示,直接在自定义文本图层中指定固定旋转角度即可(以Plotly为例):
import plotly.express as px import geopandas as gpd # 加载地理数据与可视化基础图表 gdf = gpd.read_file("your_geo_data.geojson") fig = px.choropleth_mapbox( gdf, geojson=gdf.geometry, locations=gdf.index, color="target_column", mapbox_style="carto-positron", zoom=5, center={"lat": gdf.geometry.centroid.y.mean(), "lon": gdf.geometry.centroid.x.mean()} ) # 添加垂直标签图层 fig.update_layout( mapbox={ "layers": [ { "type": "symbol", "source": {"type": "geojson", "data": gdf.__geo_interface__}, "layout": { "text-field": "{your_label_col}", # 替换为你的标签字段名 "text-size": 11, "text-rotation": 90, # 90为向上垂直,270为向下垂直 "text-anchor": "center", "text-color": "#333" } } ] }, showlegend=False # 若默认标签仍显示,可隐藏或替换 ) fig.show()
场景2:标签沿图形边缘动态旋转
要让标签随图形走向自动调整旋转角度,需先为每个地理区域计算适配的旋转角度,再绑定到图层属性:
- 计算旋转角度:利用GeoPandas获取多边形的主轴方向,转换为文本旋转角度(示例逻辑):
import numpy as np def calculate_rotation(geom): # 获取多边形的最小外接矩形,计算其角度 min_rect = geom.minimum_rotated_rectangle coords = list(min_rect.exterior.coords) vec = np.array(coords[1]) - np.array(coords[0]) angle = np.degrees(np.arctan2(vec[1], vec[0])) # 调整角度使文本沿矩形长边垂直排布 return angle + 90 if abs(angle) < 45 else angle gdf['label_rotation'] = gdf.geometry.apply(calculate_rotation)
- 绑定动态旋转角度到图层:
fig.update_layout( mapbox={ "layers": [ { "type": "symbol", "source": {"type": "geojson", "data": gdf.__geo_interface__}, "layout": { "text-field": "{your_label_col}", "text-size": 11, "text-rotation": ["get", "label_rotation"], # 调用动态计算的角度 "text-anchor": "center", "text-offset": [0, 0.3] } } ] } )
其他注意事项
- 若使用Mapbox GL JS,逻辑完全一致,在
map.addLayer()的layout配置中设置text-rotation即可。 - 可通过
text-offset调整标签与图形的距离,避免重叠。
内容的提问来源于stack exchange,提问作者Ruslan Skira
相关产品推荐
相关产品推荐

