Plotly Surface图表Hovertemplate失效问题求助
Plotly Surface图hovertemplate失效问题解决
问题原因
Plotly中Surface图的hover机制与Heatmap存在差异:Surface图会对输入的网格数据进行三角剖分,生成额外渲染点以实现曲面光滑效果;你定义的customdata仅对应原始网格的顶点数据,大部分剖分后的hover点没有匹配的customdata,导致hovertemplate无法解析变量,直接显示字面量字符串;少数能显示的顶点数据也因剖分后的索引映射问题导致数值错误。
解决方案
方案一:直接传递真实x/y数据(推荐)
无需依赖customdata,直接将真实的x、y数组传入Surface的x、y参数,即可在hovertemplate中直接调用%{x}、%{y}获取对应数值:
import plotly.graph_objects as go from plotly.offline import plot as htmly import numpy as np x = np.round(np.arange(-5,5,0.2),2) y = np.round(np.arange(0,5,0.2),2) z = np.matrix([[x[i]**2 + (y[j] - 2.5)**2 for i in range(len(x))] for j in range(len(y))]) fig = go.Figure() fig.add_trace(go.Surface( x=x, y=y, z=z, hovertemplate='<b>z:%{z:.3f}</b><br>x:%{x:.3f} <br>y: %{y:.3f} ' )) fig.update_layout( scene=dict( xaxis=dict(title='x'), yaxis=dict(title='y') ), font=dict(size=14) ) htmly(fig)
方案二:适配Surface的customdata结构(需保留customdata时使用)
若必须通过customdata传递数据,需确保customdata与Surface剖分后的点结构匹配,同时建议使用Plotly 5.0及以上版本(旧版本对Surface的customdata支持不完善)。可添加hoveron='points'参数限制hover仅触发在原始网格顶点,避免剖分点导致的customdata缺失:
import plotly.graph_objects as go from plotly.offline import plot as htmly import numpy as np x = np.round(np.arange(-5,5,0.2),2) y = np.round(np.arange(0,5,0.2),2) z = np.matrix([[x[i]**2 + (y[j] - 2.5)**2 for i in range(len(x))] for j in range(len(y))]) mesh = np.meshgrid(x,y) customdata_ = np.dstack((mesh[0], mesh[1])) fig = go.Figure() fig.add_trace(go.Surface( z=z, customdata=customdata_, hovertemplate='<b>z:%{z:.3f}</b><br>x:%{customdata[0]:.3f} <br>y: %{customdata[1]:.3f} ', hoveron='points' )) fig.update_layout( scene=dict( xaxis=dict(title='x', tickmode='array', ticktext=x, tickvals=np.arange(len(x))), yaxis=dict(title='y', tickmode='array', ticktext=y, tickvals=np.arange(len(y))) ), font=dict(size=14) ) htmly(fig)
内容的提问来源于stack exchange,提问作者dschingchris
相关产品推荐
相关产品推荐

