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

如何将Plotly分面子图的多个标题合并为单个居中标题?

解决Plotly分面柱状图合并子图标题为单个居中总标题的方法

核心思路很直接:Plotly Express生成的分面子图标题都存在fig.layout.annotations里,把这些子图注释删掉,再把总标题设为居中就行。

修改后的完整代码:

fig = px.bar(total_df, x="year", y="cases", facet_col="county_type", color="stage", text='cases', )
fig.update_traces(cliponaxis=False)
fig.update_layout(
    title_text = f'Number of Cases of {specified_cancer} Cancer with County Type (2019-2020)',
    title_x=0.5,  # 设置总标题水平居中
    yaxis_title="Total Cases",
    legend_title="Stage"
)

# 清空所有分面子图的标题注释
fig.layout.annotations = []

fig.show()

要是担心清空所有注释会影响其他元素,也可以精准只删除分面相关的标题:

# 仅移除包含"county_type="的子图标题注释
fig.layout.annotations = [anno for anno in fig.layout.annotations if 'county_type=' not in anno.get('text', '')]

这样操作后,图表就只会显示一个居中的总标题,所有分面子图的独立标题都会被移除。

内容的提问来源于stack exchange,提问作者Towphy PY

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 17:32:13