You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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'

错误原因

  1. go.Table对象本身不支持row和col属性,这两个参数属于fig.add_trace()方法的参数,而非Table对象的配置项。
  2. 使用make_subplots创建子图时,无需手动设置Table的domain,子图布局由make_subplots统一管理。
  3. 原代码中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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 08:57:42