如何让Plotly Express imshow显示自定义hover文本而非轴值?
解决Plotly Express imshow自定义hover文本的问题
你的代码存在几个关键问题,修正后即可正常显示自定义hover文本:
问题点及修正步骤
- 未传递自定义数据至imshow:原代码构造了
custom_data但未通过px.imshow的参数传入,导致hover无法读取自定义内容。 - custom_data维度错误:
np.dstack生成的是三维数组,而imshow需要与矩阵维度匹配的二维数组,每个元素对应一个单元格的自定义数据(包含x和y的product)。 - hovertemplate格式错误:product是字符串类型,不需要
.3f数值格式符,且需正确引用customdata的元素。 - 变量名不一致:定义的figure对象是
figure_test,后续却用fig调用方法,导致设置无效。
修正后的完整代码
matrix = graph_to_matrix(edf, G.nodes) x_axis = list(G.nodes) y_axis = x_axis[::-1] # 正确构造custom_data:每个单元格对应[x_product, y_product] custom_data = [] for y_node in y_axis: y_product = genome_protein_data[y_node]['product'] row = [] for x_node in x_axis: x_product = genome_protein_data[x_node]['product'] row.append([x_product, y_product]) custom_data.append(row) # 传入custom_data参数 figure_test = px.imshow(gmat[::-1], x=x_axis, y=y_axis, labels=dict(x="Target", y="Source", color="Number"), custom_data=custom_data) # 统一变量名,更新布局 figure_test.update_layout(coloraxis_colorbar_x=0.8) # 修正hovertemplate格式 figure_test.update_traces( hovertemplate="<br>".join([ "X: %{x}", "X product: %{customdata[0]}", "Y: %{y}", "Y product: %{customdata[1]}", "Number: %{z}" # 可选:显示颜色对应的数值 ]) ) figure_test.write_html('my_file.html')
关键说明
- custom_data构造逻辑:遍历y轴节点(对应矩阵行)和x轴节点(对应矩阵列),为每个单元格生成包含x、y产品名称的列表,最终形成与矩阵维度一致的二维数组。
- hovertemplate引用规则:
%{customdata[0]}对应单元格自定义数据中的第一个元素(x的product),%{customdata[1]}对应第二个元素(y的product)。 - 变量名统一:确保所有操作都针对同一个figure对象,避免因变量名错误导致配置失效。
内容的提问来源于stack exchange,提问作者Tim Kirkwood
相关产品推荐
相关产品推荐

