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

如何在Plotly Express热力图的悬浮提示中添加p值?

给Plotly热力图悬浮提示添加p值的方法

要在Plotly Express的热力图悬浮提示中加入p值,核心是通过customdata传递p值矩阵,再自定义hovertemplate调用这些数据。具体步骤如下:

1. 准备数据

假设你已经通过SciPy计算得到Spearman相关系数矩阵corr_matrix和p值矩阵p_matrix,以及特征名称列表features。如果还未生成,可参考示例代码:

import plotly.express as px
import numpy as np
from scipy.stats import spearmanr

# 示例:生成5个特征的随机数据
np.random.seed(42)
data = np.random.randn(100, 5)
features = [f"Feature_{i+1}" for i in range(5)]

# 计算Spearman相关系数与p值
corr_matrix, p_matrix = spearmanr(data)

2. 绘制热力图并自定义悬浮提示

使用px.imshow绘制热力图后,通过update_traces设置customdata和hovertemplate,将p值加入悬浮提示:

# 初始化热力图
fig = px.imshow(
    corr_matrix,
    labels=dict(x="Feature_2", y="Feature_1", color="Correlation"),
    x=features,
    y=features,
    color_continuous_scale="RdBu_r",
    zmin=-1, zmax=1  # 固定相关系数范围,提升可视化效果
)

# 自定义悬浮提示模板,引入p值
fig.update_traces(
    hovertemplate="<br>".join([
        "Feature_1: %{y}",
        "Feature_2: %{x}",
        "Correlation: %{z:.4f}",
        "p-value: %{customdata:.4f}"
    ]),
    customdata=p_matrix  # 将p值矩阵绑定到每个单元格
)

fig.show()

3. 可选:添加显著性标记

如果需要给p值添加显著性标记(如***、**、*),可先处理p值矩阵,再传入customdata:

# 生成带显著性标记的p值数组
p_with_signif = np.where(
    p_matrix < 0.001, "<0.001***",
    np.where(
        p_matrix < 0.01, "<0.01**",
        np.where(
            p_matrix < 0.05, "<0.05*",
            np.round(p_matrix, 4).astype(str)
        )
    )
)

# 更新悬浮提示
fig.update_traces(
    hovertemplate="<br>".join([
        "Feature_1: %{y}",
        "Feature_2: %{x}",
        "Correlation: %{z:.4f}",
        "p-value: %{customdata}"
    ]),
    customdata=p_with_signif
)

fig.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 05:15:29