Plotly Heatmap的texttemplate无法调用customdata问题求助
Plotly热力图texttemplate引用customdata失效的解决方法
问题原因
Plotly热力图的texttemplate默认绑定text属性渲染内容,而hovertemplate可直接引用customdata是因为悬停交互的变量范围包含自定义数据,二者逻辑不同。若未正确关联customdata与text属性,texttemplate就无法正常显示customdata内容。
解决方案
方案一(兼容性更强)
将customdata赋值给text属性,再通过texttemplate格式化显示,适配你使用的Plotly 5.15.0版本:
import plotly.express as px import numpy df = px.data.medals_wide(indexed=True) fig = px.imshow(df) customdata = numpy.zeros(df.shape) fig.data[0].customdata = customdata fig.data[0].hovertemplate = 'Custom data: %{customdata}' # 悬停模板正常生效 fig.data[0].text = customdata # 将自定义数据绑定到text属性 fig.data[0].texttemplate = '%{text}' # 通过texttemplate显示customdata内容 fig.write_html('deleteme.html',include_plotlyjs='cdn')
方案二(直接引用customdata)
确保开启文本显示,并初始化text属性后,直接在texttemplate中引用customdata:
import plotly.express as px import numpy df = px.data.medals_wide(indexed=True) fig = px.imshow(df) customdata = numpy.zeros(df.shape) fig.data[0].customdata = customdata fig.data[0].hovertemplate = 'Custom data: %{customdata}' fig.data[0].showtext = True # 强制开启文本显示 fig.data[0].text = customdata # 初始化text属性 fig.data[0].texttemplate = '%{customdata}' fig.write_html('deleteme.html',include_plotlyjs='cdn')
效果说明
修改后热力图单元格将显示customdata的内容(示例中为0),与预期效果一致。
内容的提问来源于stack exchange,提问作者user171780
相关产品推荐
相关产品推荐

