Plotly Choroplethmapbox子图无法分栏显示问题求助
问题描述
想要绘制两张哥伦比亚地图子图,分别展示汇总数值cases及其log10转换后的值,但只有将两个Choroplethmapbox trace都设置为row=1, col=1时才能正常显示,分开设置子图位置时无法工作。
原代码
import plotly.graph_objects as go from plotly.subplots import make_subplots import numpy as np locs = dfd['department'] for loc in counties['features']: loc['id'] = loc['properties']['NOMBRE_DPT'] fig = make_subplots( rows=1, cols=2, subplot_titles=['Normal distribution', 'Logarithm 10'], specs=[[{"type": "mapbox"}, {"type": "mapbox"}]] ) fig.add_trace(go.Choroplethmapbox( geojson=counties, locations=dfd['department'], z=dfd['cases'], colorbar_title = 'First', colorbar=dict(thickness=20, x=0.46), marker=dict(opacity=0.75)), row=1, col=1) fig.add_trace(go.Choroplethmapbox( geojson=counties, locations=dfd['department'], z=np.log10(dfd['cases']), colorbar_title = 'Second', colorbar=dict(thickness=20, x=1.02), marker=dict(opacity=0.75)), row=1, col=1) fig.update_layout(margin=dict(l=20, r=0, t=40, b=40)) fig.update_layout(mapbox1=dict(zoom=3.4, style='carto-positron'), mapbox2=dict(zoom=3.4, style='light'), mapbox_center = {"lat": 4.570868, "lon": -74.2973328}) fig.show()
解决方案
问题核心是Mapbox子图的独立配置缺失,修改以下两点即可解决:
为每个子图单独设置地图中心
原代码中mapbox_center是全局配置,仅会作用于第一个子图,需要为mapbox1和mapbox2分别添加center参数,确保两张地图都能定位到哥伦比亚区域。正确分配trace到对应子图
将第二个Choroplethmapbox的row=1, col=1改为row=1, col=2,同时微调colorbar的x坐标,避免两个颜色条重叠或超出子图范围。
修改后的完整代码
import plotly.graph_objects as go from plotly.subplots import make_subplots import numpy as np locs = dfd['department'] for loc in counties['features']: loc['id'] = loc['properties']['NOMBRE_DPT'] fig = make_subplots( rows=1, cols=2, subplot_titles=['Normal distribution', 'Logarithm 10'], specs=[[{"type": "mapbox"}, {"type": "mapbox"}]] ) # 添加第一个子图:原始cases数值 fig.add_trace(go.Choroplethmapbox( geojson=counties, locations=dfd['department'], z=dfd['cases'], colorbar_title = 'Cases', colorbar=dict(thickness=20, x=0.45), marker=dict(opacity=0.75)), row=1, col=1) # 添加第二个子图:log10转换后的数值 fig.add_trace(go.Choroplethmapbox( geojson=counties, locations=dfd['department'], z=np.log10(dfd['cases']), colorbar_title = 'Log10(Cases)', colorbar=dict(thickness=20, x=1.0), marker=dict(opacity=0.75)), row=1, col=2) # 调整整体边距,避免内容被截断 fig.update_layout(margin=dict(l=20, r=20, t=40, b=40)) # 分别配置两个子图的地图参数 fig.update_layout( mapbox1=dict( zoom=3.4, style='carto-positron', center={"lat": 4.570868, "lon": -74.2973328} ), mapbox2=dict( zoom=3.4, style='light', center={"lat": 4.570868, "lon": -74.2973328} ) ) fig.show()
关键说明
- Plotly的Mapbox子图是独立实例,每个
mapboxN(N为子图序号)需要单独配置缩放、中心、样式等参数,全局的mapbox_*配置不会自动应用到所有子图。 - colorbar的x坐标需要根据子图布局调整,第一个子图的colorbar x值设置在0.4-0.45之间,第二个子图设置在0.95-1.0之间,既能避免重叠,又能保证显示在子图右侧。
内容的提问来源于stack exchange,提问作者Estiven
相关产品推荐
相关产品推荐

