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

Plotly自定义悬停文本时如何保留反色显示的曲线名称?

Plotly自定义悬停文本同时保留反色曲线名称的解决方法

核心修改

将data1轨迹的hoverinfo='text'替换为hoverinfo='name+text',即可同时显示反色曲线名称和自定义悬停文本。

修改后的完整代码

import plotly.graph_objects as go
import pandas as pd

# Create a DataFrame with X, Y, and f values
df= pd.DataFrame({'x': [1, 2, 3, 4, 5], 'y': [10, 12, 5, 8, 6], 'x2': [1, 3, 4, 5, 7],'y2':[2,5,3,1,8],'f':[1,2,3,4,5]})

hover_text1 = df.apply(lambda row: f'({row["x"]},{row["y"]}) at {row["f"]}', axis=1)
fig=go.Figure()
# 修改hoverinfo为name+text,保留反色名称
fig.add_trace(go.Scatter(x=df.x, y= df.y, mode='lines+markers', text=hover_text1, name='data1', 
                         line=dict(color='orange',width=2),marker=dict(symbol='circle', size=10),
                         hoverinfo='name+text'))
fig.add_trace(go.Scatter(x=df.x2, y= df.y2, mode='lines+markers', name='data2', 
                         line=dict(color='green',width=2),marker=dict(symbol='circle', size=10)))

# Customize the layout or add additional settings as needed
fig.update_layout(title='Plotly Scatter Plot', xaxis_title='X-axis', yaxis_title='Y-axis', showlegend=True)

# Show the plot
fig.show()

原理说明

  • 原代码中hoverinfo='text'会强制悬停框仅展示自定义的text内容,屏蔽了默认的曲线名称显示。
  • 设置hoverinfo='name+text'后,Plotly会自动在悬停框顶部以反色样式展示曲线名称(即name='data1'的内容),下方显示你自定义的hover_text1文本,完全匹配data2的悬停样式逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 09:43:22