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

如何在Python Plotly图表中自定义悬停显示多维度数据?

解决Plotly双Y轴散点图自定义悬停提示问题

问题说明

使用Python Plotly绘制双Y轴散点图时,悬停提示框显示的信息不符合需求,希望鼠标悬停在数据点时显示以下信息:

  • RacerCount:对应数据点的赛事参赛人数
  • Velocity:该点的速度值
  • Counts:同参赛人数下的赛事统计数
  • WinLoss:同参赛人数下的胜负总和
  • Positives:同参赛人数下的胜场总和
  • Negatives:同参赛人数下的负场总和

修改后的可行代码

import pandas as pd
import numpy as np
import plotly.graph_objects as go
from plotly.subplots import make_subplots

# 读取数据,保留RacerCount为列(避免索引合并问题)
df = pd.read_csv("resultant_data.txt", sep=",")

# 定义聚合函数
pos = lambda col : col[col > 0].sum()
neg = lambda col : col[col < 0].sum()

# 按RacerCount聚合统计,重置索引方便后续合并
Related_Display_Info = df.groupby("RacerCount").agg(
    Counts=("Velocity","count"), 
    WinLoss=("WinLoss","sum"),
    Positives=("WinLoss", pos),
    Negatives=("WinLoss", neg)
).reset_index()

# 将聚合结果合并到原始数据,确保每个数据点都携带统计信息
merged_df = pd.merge(df, Related_Display_Info, on="RacerCount", how="left")

# 创建双Y轴图表
fig = make_subplots(specs=[[{"secondary_y": True}]])

# 添加Velocity散点轨迹,自定义悬停提示
fig.add_trace(
    go.Scatter(
        x=merged_df["RacerCount"], 
        y=merged_df["Velocity"], 
        name="Velocity", 
        mode="markers",
        # 传递需要展示的自定义字段
        customdata=merged_df[["RacerCount", "Counts", "WinLoss", "Positives", "Negatives"]],
        # 定制悬停提示格式
        hovertemplate=(
            "RacerCount: %{customdata[0]}<br>"
            "Velocity: %{y:.2f}<br>"
            "Counts: %{customdata[1]}<br>"
            "WinLoss: %{customdata[2]}<br>"
            "Positives: %{customdata[3]}<br>"
            "Negatives: %{customdata[4]}<br>"
            "<extra></extra>"  # 隐藏默认轨迹名称
        )
    ),
    secondary_y=False
)

# 添加Win/Loss散点轨迹,自定义悬停提示
fig.add_trace(
    go.Scatter(
        x=Related_Display_Info["RacerCount"], 
        y=Related_Display_Info["WinLoss"],
        name="Win/Loss", 
        mode="markers",
        marker=dict(
            color=(Related_Display_Info["WinLoss"] < 0).astype('int'),
            colorscale=[[0, 'green'], [1, 'red']]
        ),
        customdata=Related_Display_Info[["RacerCount", "Counts", "Positives", "Negatives"]],
        hovertemplate=(
            "RacerCount: %{customdata[0]}<br>"
            "WinLoss: %{y}<br>"
            "Counts: %{customdata[1]}<br>"
            "Positives: %{customdata[2]}<br>"
            "Negatives: %{customdata[3]}<br>"
            "<extra></extra>"
        )
    ),
    secondary_y=True,
)

# 配置图表样式
fig.update_layout(
    title_text="Race Analysis",
    hovermode="x unified"  # 同一x值的点共享悬停提示
)

fig.update_xaxes(title_text="<b>Racer Counts</b>")
fig.update_yaxes(title_text="<b>Velocity</b>", secondary_y=False)
fig.update_yaxes(title_text="<b>Win/Loss</b>", secondary_y=True)

fig.show()

关键修改说明

  1. 数据关联:将聚合后的统计结果与原始数据合并,让每个散点都能获取到对应RacerCount的所有统计值,解决了原始代码中统计数据与散点数据脱节的问题。
  2. 自定义悬停模板:通过customdata传递需要展示的额外字段,再用hovertemplate精准控制提示内容的格式和排版,完全匹配需求中的显示字段。
  3. 索引处理:取消index_col=0设置,保留RacerCount为普通列,避免后续数据合并时的索引冲突;如果必须使用索引,可通过reset_index()将索引转回列。
  4. 统一悬停模式:保留hovermode="x unified",确保同一参赛人数的所有数据点悬停时,能展示完整的关联统计信息。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 22:50:27