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

Plotly imshow中图像数组文本注释的顺序控制问题

解决Plotly imshow中Facet注释顺序混乱的问题

你遇到的问题核心是Plotly生成的facet注释(annotations)列表的顺序不是视觉上的行优先顺序,而是列优先顺序。你的10个图像按5列2行排列时,annotations列表的顺序是[0,5,1,6,2,7,3,8,4,9](先列0的两行,再列1的两行,以此类推),而你用enumerate直接赋值时,相当于把第1个注释(对应视觉上的第0号图)设为"0",第2个注释(对应视觉上的第5号图)设为"1",自然就出现了顺序混乱。


解决方案

方案1:复用默认注释的原始索引

Plotly的px.imshow生成的facet注释默认已经对应X数组的索引(比如第0号图的注释文本是"0"),如果只是想保留索引作为注释,完全不需要手动修改:

fig = px.imshow(X[:, :, :], binary_string=False, zmin=0, zmax=1,
            facet_col=0, aspect='auto', facet_col_wrap=5,
            facet_row_spacing=0, color_continuous_scale='rdylgn')
# 直接保留默认注释即可
fig.show()

如果需要修改注释格式(比如加上前缀),可以基于原始注释的文本修改:

for ann in fig.layout.annotations:
    ann['text'] = f"样本{ann['text']}"

方案2:按列优先顺序映射数组索引

如果需要手动控制注释文本,可以先生成符合Plotly注释顺序的索引列表,再赋值:

from dash import Dash, dcc, html, Input, Output,callback
import plotly.express as px
import numpy as np

X = np.zeros((10,28,28))
y = np.zeros(10,)

for i in range(10):
   X[i,::,::] = i/10
   y[i] = i

fig = px.imshow(X[:, :, :], binary_string=False, zmin=0, zmax=1,
            facet_col=0, aspect='auto', facet_col_wrap=5,
            facet_row_spacing=0, color_continuous_scale='rdylgn')

# 生成符合Plotly注释顺序的索引列表(列优先)
cols = 5
total_samples = len(X)
rows = (total_samples + cols - 1) // cols  # 计算行数
annotation_indices = []
for col in range(cols):
    for row in range(rows):
        idx = row * cols + col
        if idx < total_samples:
            annotation_indices.append(idx)

# 按顺序设置注释文本
for n, ann in enumerate(fig.layout.annotations):
    ann['text'] = str(annotation_indices[n])

fig.show()

这样修改后,左上角的第0号图注释为"0",右下角的第9号图注释为"9",完全匹配视觉顺序。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 04:35:57