如何在Python Plotly中实现图例项悬停显示文本?
Plotly图例项添加悬停文本的实现方法
问题背景
因为轨迹真实名称过长,我在Plotly中使用了"trace 0"这类短名称显示图例,但希望悬停图例项时能弹出对应的真实名称(比如悬停"trace 0"时显示"the y value is the square of x")。查了官方文档没找到直接配置的方法,想问Plotly是否支持这个功能?
示例代码:
import plotly.graph_objects as go trace_0_name = "the y value is the square of x" trace_1_name = "the y value is the cube of x" fig = go.Figure() fig.add_trace(go.Scatter(x=[1,2,3], y=[1,2**2,3**2])) fig.add_trace(go.Scatter(x=[1,2,3], y=[1,2**3,3**3])) fig.show()
解决方案
Plotly原生没有直接配置图例悬停文本的参数,但可以通过以下两种方式实现需求:
方法1:使用Dash框架实现(适合Web应用)
Dash可以监听图例的hover事件,动态显示自定义提示框:
import dash from dash import dcc, html, Input, Output, State import plotly.graph_objects as go trace_0_name = "the y value is the square of x" trace_1_name = "the y value is the cube of x" fig = go.Figure() fig.add_trace(go.Scatter(x=[1,2,3], y=[1,2**2,3**2], name="trace 0")) fig.add_trace(go.Scatter(x=[1,2,3], y=[1,2**3,3**3], name="trace 1")) app = dash.Dash(__name__) app.layout = html.Div([ dcc.Graph(id='graph', figure=fig), html.Div( id='legend-tooltip', style={ 'position': 'absolute', 'visibility': 'hidden', 'background': 'white', 'padding': '8px', 'border': '1px solid #ccc', 'border-radius': '4px', 'z-index': 1000 } ) ]) @app.callback( [Output('legend-tooltip', 'style'), Output('legend-tooltip', 'children')], Input('graph', 'hoverData'), State('legend-tooltip', 'style') ) def update_tooltip(hoverData, style): if hoverData and 'curveNumber' in hoverData['points'][0]: curve_num = hoverData['points'][0]['curveNumber'] tooltip_text = trace_0_name if curve_num == 0 else trace_1_name style['visibility'] = 'visible' # 根据鼠标位置调整提示框位置 style['top'] = f"{hoverData['points'][0]['y'] + 10}px" style['left'] = f"{hoverData['points'][0]['x'] + 10}px" return style, tooltip_text else: style['visibility'] = 'hidden' return style, "" if __name__ == '__main__': app.run_server(debug=True)
方法2:纯Plotly通过JavaScript回调实现(适合非Dash场景)
如果不需要构建Web应用,可以给图表添加JavaScript回调,监听图例的鼠标悬停事件:
import plotly.graph_objects as go trace_0_name = "the y value is the square of x" trace_1_name = "the y value is the cube of x" fig = go.Figure() fig.add_trace(go.Scatter(x=[1,2,3], y=[1,2**2,3**2], name="trace 0")) fig.add_trace(go.Scatter(x=[1,2,3], y=[1,2**3,3**3], name="trace 1")) # 添加JavaScript回调实现图例悬停提示 fig.add_js_callback( """ function(gd) { // 创建提示框元素 const tooltip = document.createElement('div'); Object.assign(tooltip.style, { position: 'absolute', visibility: 'hidden', backgroundColor: 'white', padding: '8px', border: '1px solid #ccc', borderRadius: '4px', pointerEvents: 'none', zIndex: 1000 }); gd.appendChild(tooltip); // 绑定轨迹名称 const traceNames = ['""" + trace_0_name + """', '""" + trace_1_name + """']; const legendItems = gd.querySelectorAll('.legenditem'); // 给每个图例项添加悬停事件 legendItems.forEach((item, index) => { item.addEventListener('mouseover', (e) => { tooltip.textContent = traceNames[index]; tooltip.style.visibility = 'visible'; tooltip.style.top = `${e.pageY + 10}px`; tooltip.style.left = `${e.pageX + 10}px`; }); item.addEventListener('mouseout', () => { tooltip.style.visibility = 'hidden'; }); }); } """ ) fig.show()
说明
两种方法都能实现图例悬停显示真实名称的需求:
- Dash方法适合需要构建完整交互式Web应用的场景,功能扩展更灵活;
- 纯Plotly方法适合快速生成带交互的静态图表,无需额外搭建Web服务。
内容的提问来源于stack exchange,提问作者nPn
相关产品推荐
相关产品推荐

