使用Plotly Choropleth绘制大量多边形并移除背景地图
解决方法及等效方案
一、移除现有choropleth的背景地图
你的代码方向没问题,要去掉背景地图,只需在现有代码中添加update_geos配置,隐藏地理图层并让视图自动适配多边形范围:
修改后的完整代码:
import plotly.express as px polygons = [[(1, 1), (1, 2), (2, 2), (2, 1), (1, 1)], [(3, 3), (3, 4), (4, 4), (4, 3), (3, 3)], [(5, 5), (5, 6), (6, 6), (6, 5), (5, 5)], [(7, 7), (7, 8), (8, 8), (8, 7), (7, 7)]] geojson = {'features': [], 'type': 'FeatureCollection'} ids = [] for index, poly in enumerate(polygons): temp_dict = { 'geometry': { 'coordinates': [polygons[index].copy()], 'type': 'Polygon'}, 'type': 'Feature', 'id': index} geojson['features'].append(temp_dict) ids.append(index) fig = px.choropleth( geojson=geojson, color=ids, locations=ids) fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0}) # 核心配置:隐藏背景地图,自动适配多边形范围 fig.update_geos(visible=False, fitbounds="locations") fig.show()
visible=False会完全隐藏地理底图,fitbounds="locations"会让图表自动缩放至所有多边形的边界范围,避免出现空白或显示不全的问题。
二、更适合非地理多边形的等效方案
虽然choropleth能满足需求,但它本质是为地理数据设计的组件。如果需要更纯粹的笛卡尔坐标系可视化,且保持批量渲染的高性能,可以用以下两种方案:
方案1:使用go.Choropleth(性能和px版本一致)
import plotly.graph_objects as go # 复用你之前构建的geojson和ids fig = go.Figure(go.Choropleth( geojson=geojson, locations=ids, z=ids, colorscale='Viridis' )) fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0}) fig.update_geos(visible=False, fitbounds="locations") fig.show()
方案2:Scatter填充(适合少量多边形,或需要更灵活样式)
如果多边形数量不多,也可以用Scatter的fill='toself'来绘制,样式调整更灵活:
import plotly.graph_objects as go import plotly.express as px fig = go.Figure() color_palette = px.colors.qualitative.Plotly for idx, poly in enumerate(polygons): x_coords, y_coords = zip(*poly) fig.add_trace(go.Scatter( x=x_coords, y=y_coords, fill='toself', fillcolor=color_palette[idx % len(color_palette)], line={'color': 'black'}, showlegend=False )) fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0}) fig.update_xaxes(visible=False) fig.update_yaxes(visible=False) fig.show()
注意:这个方案是逐个添加trace,多边形数量极大时性能会不如基于geojson的批量渲染方式。
内容的提问来源于stack exchange,提问作者fontanf
相关产品推荐
相关产品推荐

