
Plotly 默认子图类型为笛卡尔坐标系(xy),而三元图需显式指定 subplot type 为 "ternary";使用 make_subplots(specs=[...]) 可正确构建多三元图布局,但 px.scatter_ternary 目前不支持 facet 子图。
plotly 默认子图类型为笛卡尔坐标系(xy),而三元图需显式指定 subplot type 为 "ternary";使用 `make_subplots(specs=[...])` 可正确构建多三元图布局,但 `px.scatter_ternary` 目前不支持 facet 子图。
在 Plotly 中实现三元图(ternary plot)的子图布局,关键在于理解 make_subplots() 的 specs 参数机制。默认情况下,make_subplots(rows=1, cols=2) 会为每个子图分配 "type": "xy",因此当尝试添加 go.Scatterternary 这类非笛卡尔迹(trace)时,便会触发错误:
ValueError: Trace type 'scatterternary' is not compatible with subplot type 'xy'
✅ 正确做法是:为每个需要承载三元图的子图位置显式声明 {"type": "ternary"}。例如,构建并排双三元图,应这样初始化:
from plotly.subplots import make_subplots
import plotly.graph_objects as go
# 示例数据(已结构化)
rawData = [
{'journalist':75,'developer':25,'designer':0,'label':'point 1'},
{'journalist':70,'developer':10,'designer':20,'label':'point 2'},
# ... 其余数据保持不变
]
# 提取坐标列(推荐用列表推导式或 pandas 更简洁)
a_vals = [d['journalist'] for d in rawData]
b_vals = [d['developer'] for d in rawData]
c_vals = [d['designer'] for d in rawData]
labels = [d['label'] for d in rawData]
# 定义统一的三元轴样式(可复用)
def makeAxis(title, tickangle):
return {
'title': {'text': title, 'font': {'size': 16}},
'tickangle': tickangle,
'tickfont': {'size': 13},
'showgrid': True,
'showline': True
}
# ✅ 关键:指定 specs,让每列子图都支持 ternary 类型
fig = make_subplots(
rows=1, cols=2,
specs=[[{"type": "ternary"}, {"type": "ternary"}]], # ← 必须!
subplot_titles=("Team Role Distribution A", "Team Role Distribution B")
)
# 添加两个相同的三元散点图(可替换为不同数据集)
fig.add_trace(
go.Scatterternary(
a=a_vals, b=b_vals, c=c_vals,
text=labels,
mode='markers',
marker=dict(
symbol='circle',
color='#DB7365',
size=12,
line=dict(width=1.5, color='white')
)
),
row=1, col=1
)
fig.add_trace(
go.Scatterternary(
a=[x*0.8 for x in a_vals], # 演示:右侧图稍作变换(如缩放)
b=[x*1.1 for x in b_vals],
c=c_vals,
text=labels,
mode='markers',
marker=dict(
symbol='diamond',
color='#3498db',
size=14,
line=dict(width=1.5, color='white')
)
),
row=1, col=2
)
# 统一配置三元坐标系(注意:需对每个 subplot 单独设置,或使用 update_ternary)
fig.update_layout(
height=500,
title_text="Side-by-Side Ternary Subplots",
ternary_aaxis=makeAxis('Journalist', 0),
ternary_baxis=makeAxis('<br>Developer', 45),
ternary_caxis=makeAxis('<br>Designer', -45),
# ⚠️ 注意:update_layout 中的 ternary_*axis 是全局默认值;
# 若需为不同子图定制轴(如不同标题/刻度),需使用 fig.update_ternary() + selector
)
fig.show()
? 重要说明与限制:
-
plotly.express.scatter_ternary()不支持facet_row/facet_col等分面参数(截至 Plotly v6.x),因此无法像px.scatter()那样一键生成分面三元图。必须使用graph_objects+make_subplots手动组合。 - 若需混合其他类型图表(如左侧 ternary、右侧直方图),只需在对应
specs中混合声明类型,例如:specs=[[{"type": "ternary"}, {"type": "xy"}]],然后分别添加Scatterternary和Bar/Histogram等迹。 - 不支持将 Plotly 图嵌入 Matplotlib 的
ax对象(二者渲染引擎不同);跨库混用需通过图像导出(如fig.write_image("plot.png"))或 Dash 应用集成。
? 最佳实践建议:
- 始终在调用
make_subplots()时明确specs,避免隐式假设; - 使用
subplot_titles提升可读性; - 对多个三元图,可通过
fig.update_ternary(selector=dict(row=1, col=1))精细控制单个子图属性; - 数据预处理推荐使用
pandas(如df[['a','b','c']].values.T.tolist()),提升可读性与健壮性。
掌握 specs 参数,即可自由组合任意 Plotly 支持的子图类型——三元图子图,不再“迷路”。










