如何将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
相关产品推荐
相关产品推荐

