Plotly中如何将Table与Scattermapbox设为子图并调整尺寸?
解决Plotly中Table子图添加时的row属性报错问题
问题说明
需要在单个Plotly图表中同时嵌入Table和Scattermapbox子图,要求Scattermapbox的尺寸为Table的3倍,但添加Table子图时触发以下错误:
ValueError: Invalid property specified for object of type plotly.graph_objs.Table: 'row'
错误原因
go.Table对象本身不支持row和col属性,这两个参数属于fig.add_trace()方法的参数,而非Table对象的配置项。- 使用
make_subplots创建子图时,无需手动设置Table的domain,子图布局由make_subplots统一管理。 - 原代码中
specs里的子图类型设置为choroplethmapbox,但实际添加的是Scattermapbox,类型不匹配。
修正后的代码
import plotly.graph_objects as go from plotly.subplots import make_subplots # 补充导入make_subplots import pandas as pd mapboxtoken = "pk.eyJ1IjoianBhbGV4MTIzIiwiYSI6ImNsN3NsemlieTA0ZGszdnAzNHRzb3k4emkifQ.DOmCc34Bj1t4zG6O5yVzoA" mapboxstyle = 'mapbox://styles/jpalex123/cl7sp1tou001q14qtcjt5ndhn' df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/Nuclear%20Waste%20Sites%20on%20American%20Campuses.csv') site_lat = df.lat site_lon = df.lon locations_name = df.text # 创建子图,通过row_heights设置高度比例(1:3) fig = make_subplots( rows=2, cols=1, subplot_titles=('Table', 'Scatter Map'), specs=[[{"type": "table"}], [{"type": "scattermapbox"}]], # 修正子图类型为scattermapbox row_heights=[0.25, 0.75] # 表格占1/4,地图占3/4,实现3倍尺寸关系 ) # 添加Table子图,将row和col放在add_trace方法中 fig.add_trace(go.Table( header=dict(values=['A Scores', 'B Scores']), cells=dict(values=[[100, 90, 80, 90], [95, 85, 75, 95]]) ), row=1, col=1) # row和col参数在这里设置 # 添加Scattermapbox子图 fig.add_trace(go.Scattermapbox( lat=site_lat, lon=site_lon, mode='markers', marker=go.scattermapbox.Marker( size=17, color='rgb(255, 0, 0)', opacity=0.7 ), text=locations_name, hoverinfo='text' ), row=2, col=1) # 配置地图样式和token fig.update_layout( mapbox1_accesstoken=mapboxtoken, mapbox1=dict(zoom=1, style=mapboxstyle), height=800 # 可选:设置整体图表高度,让子图比例更直观 ) fig.show()
关键修改点
- 补充导入
make_subplots模块(原代码遗漏该导入)。 - 通过
row_heights参数设置子图高度比例,实现地图尺寸为表格的3倍。 - 将
row和col参数从go.Table的配置中移至fig.add_trace()方法内。 - 修正
specs中的子图类型为scattermapbox,与添加的子图类型匹配。 - 移除Table的
domain配置,交由make_subplots管理布局。
内容的提问来源于stack exchange,提问作者Chopin
相关产品推荐
相关产品推荐

