如何为包含图像的Plotly子图添加独立标题(禁用plotly.express)
Plotly 纵向子图独立标题添加方案
问题场景
参考官方基础图像示例编写代码,创建了3个纵向排列的图像子图,初始实现代码如下:
import plotly.graph_objects as go from plotly.subplots import make_subplots imgs_rgb = ( [[[255, 0, 0], [0, 255, 0], [0, 0, 255]], [[0, 255, 0], [0, 0, 255], [255, 0, 0]]], [[[255, 127, 0], [127, 255, 0], [127, 0, 255]], [[127, 255, 0], [127, 0, 255], [255, 127, 0]]], [[[0, 255, 255], [0, 255, 127], [255, 0, 255]], [[255, 255, 0], [0, 255, 255], [127, 255, 0]]], ) fig = make_subplots(rows=len(imgs_rgb), cols=1) for row, img_rgb in enumerate(imgs_rgb): fig.add_trace( go.Image(z=img_rgb), row=row+1, col=1 ) fig.show()
需要为每个独立子图添加对应的标题/标签,实现类似分面图像的展示效果,预期效果参考:
约束说明:当前环境未安装
plotly.express,无法使用该模块的相关功能实现需求。
实现方法
直接使用make_subplots原生支持的subplot_titles参数即可完成需求,无需依赖plotly.express模块,操作要点如下:
- 在初始化子图布局时,传入按子图排列顺序存储的标题列表
- 如需调整标题样式,可通过
update_annotations统一配置,或单独修改fig.layout.annotations中对应索引的标题属性
修改后的完整代码:
import plotly.graph_objects as go from plotly.subplots import make_subplots imgs_rgb = ( [[[255, 0, 0], [0, 255, 0], [0, 0, 255]], [[0, 255, 0], [0, 0, 255], [255, 0, 0]]], [[[255, 127, 0], [127, 255, 0], [127, 0, 255]], [[127, 255, 0], [127, 0, 255], [255, 127, 0]]], [[[0, 255, 255], [0, 255, 127], [255, 0, 255]], [[255, 255, 0], [0, 255, 255], [127, 255, 0]]], ) # 按从上到下的子图顺序传入对应标题 sub_titles = ["基础RGB色块图", "半阶偏移色块图", "混色偏移色块图"] fig = make_subplots( rows=len(imgs_rgb), cols=1, subplot_titles=sub_titles ) for row, img_rgb in enumerate(imgs_rgb): fig.add_trace( go.Image(z=img_rgb), row=row+1, col=1 ) # 可选:统一调整子标题字体大小 fig.update_annotations(font_size=12) fig.show()
注意事项
subplot_titles的元素顺序严格匹配子图排列规则:单列纵向布局时从上到下对应列表元素顺序,多列布局时按先行后列的顺序匹配- 如需单独调整某一个子标题的位置、颜色、字体,可通过索引访问
fig.layout.annotations[i]修改对应属性即可
内容的提问来源于stack exchange,提问作者FriendFX
相关产品推荐
相关产品推荐

