Plotly如何在悬停框中额外显示Diff列的数值
在Plotly面积子图的统一悬停框中添加差值(Diff)显示
我有两个面积子图,鼠标悬停时会显示Val_2和Val_Yellow的数值。数据框里有一列名为Diff,存储的是Val_2与Val_Yellow的差值。请问怎么在显示这两个值的同一白色悬停框底部,展示Diff及其对应数值?

可复现代码
import numpy as np import pandas as pd import plotly.graph_objects as go from plotly.subplots import make_subplots rng = pd.date_range('2022-04-09', periods=20, freq='D') np.random.seed(42) first_df = pd.DataFrame({ 'Date': rng, 'Val' : np.random.randn(len(rng))}) first_df['Type'] = 'A' second_df = pd.DataFrame({ 'Date': rng, 'Val' : np.random.randn(len(rng))}) second_df['Type'] = 'B' final_df = pd.concat([first_df,second_df]).sort_values(by = 'Date') final_df['Is_Weekend'] = np.where((final_df['Date'].dt.weekday == 5), 1, 0 ) final_df['Val_2'] = final_df['Val'] * 3 final_df['Diff'] = final_df['Val'] - final_df['Val_2'] A_df = final_df[final_df['Type']=='A'] B_df = final_df[final_df['Type']=='B'] fig = make_subplots(rows=2, cols=1, vertical_spacing = 0.05, shared_xaxes=True) fig.add_trace(go.Scatter( x = A_df['Date'], y = A_df['Val'], fill=None, mode='lines+markers', line_color='orange', showlegend=True, name = "Val_Yellow"), row = 1, col = 1) fig.add_trace(go.Scatter( x = A_df['Date'], y = A_df['Val_2'], fill='tonexty', # fill area mode='lines+markers', line_color='red', showlegend=False, name ="Val_2"), row = 1, col = 1) fig.update_xaxes(showgrid=False, row=1, col=1) fig.add_trace(go.Scatter( x = B_df['Date'], y = B_df['Val'], fill=None, mode='lines+markers', line_color='blue', showlegend=True, name = "Val_Blue"), row = 2, col = 1) fig.add_trace(go.Scatter( x = B_df['Date'], y = B_df['Val_2'], fill='tonexty', # fill area mode='lines+markers', line_color='red', showlegend=True, name ="Val_2"), row = 2, col = 1) fig.update_yaxes(tickprefix = "$") fig.update_layout(hovermode='x unified', xaxis_range=[A_df['Date'].iloc[0], A_df['Date'].iloc[len(A_df)-1]])
解决方案
要在统一悬停框中添加Diff值,可通过customdata传递差值数据,配合hovertemplate自定义悬停显示内容,具体修改后的代码如下:
import numpy as np import pandas as pd import plotly.graph_objects as go from plotly.subplots import make_subplots rng = pd.date_range('2022-04-09', periods=20, freq='D') np.random.seed(42) first_df = pd.DataFrame({ 'Date': rng, 'Val' : np.random.randn(len(rng))}) first_df['Type'] = 'A' second_df = pd.DataFrame({ 'Date': rng, 'Val' : np.random.randn(len(rng))}) second_df['Type'] = 'B' final_df = pd.concat([first_df,second_df]).sort_values(by = 'Date') final_df['Is_Weekend'] = np.where((final_df['Date'].dt.weekday == 5), 1, 0 ) final_df['Val_2'] = final_df['Val'] * 3 final_df['Diff'] = final_df['Val'] - final_df['Val_2'] A_df = final_df[final_df['Type']=='A'] B_df = final_df[final_df['Type']=='B'] fig = make_subplots(rows=2, cols=1, vertical_spacing = 0.05, shared_xaxes=True) # 第一行子图:Val_Yellow,添加Diff数据和自定义悬停模板 fig.add_trace(go.Scatter( x = A_df['Date'], y = A_df['Val'], fill=None, mode='lines+markers', line_color='orange', showlegend=True, name = "Val_Yellow", customdata = A_df['Diff'], hovertemplate = '<b>Val_Yellow</b>: $%{y:.2f}<br>' + '<b>Diff</b>: $%{customdata:.2f}<extra></extra>' ), row = 1, col = 1) # 第一行子图:Val_2,自定义悬停模板 fig.add_trace(go.Scatter( x = A_df['Date'], y = A_df['Val_2'], fill='tonexty', mode='lines+markers', line_color='red', showlegend=False, name ="Val_2", hovertemplate = '<b>Val_2</b>: $%{y:.2f}<extra></extra>' ), row = 1, col = 1) fig.update_xaxes(showgrid=False, row=1, col=1) # 第二行子图:Val_Blue,添加Diff数据和自定义悬停模板 fig.add_trace(go.Scatter( x = B_df['Date'], y = B_df['Val'], fill=None, mode='lines+markers', line_color='blue', showlegend=True, name = "Val_Blue", customdata = B_df['Diff'], hovertemplate = '<b>Val_Blue</b>: $%{y:.2f}<br>' + '<b>Diff</b>: $%{customdata:.2f}<extra></extra>' ), row = 2, col = 1) # 第二行子图:Val_2,自定义悬停模板 fig.add_trace(go.Scatter( x = B_df['Date'], y = B_df['Val_2'], fill='tonexty', mode='lines+markers', line_color='red', showlegend=True, name ="Val_2", hovertemplate = '<b>Val_2</b>: $%{y:.2f}<extra></extra>' ), row = 2, col = 1) fig.update_yaxes(tickprefix = "$") fig.update_layout(hovermode='x unified', xaxis_range=[A_df['Date'].iloc[0], A_df['Date'].iloc[-1]]) fig.show()
关键说明
customdata:将Diff列数据传入Trace,作为悬停时的额外显示内容hovertemplate:自定义悬停文本格式,%{y}对应y轴数值,%{customdata}对应传入的Diff值,<extra></extra>用于隐藏默认的Trace名称- 由于启用了
hovermode='x unified',同一x轴位置的所有Trace悬停内容会合并到一个框中,Diff值会自动显示在框的底部
内容的提问来源于stack exchange,提问作者user9532692
相关产品推荐
相关产品推荐

