如何在Plotly散点图hoverTemplate中用变量替换硬编码列索引
解决方案
你可以通过Python的字符串格式化功能,把变量bollSpreadCol动态插入到hovertemplate字符串中,推荐使用f-string(Python 3.6及以上版本支持),写法简洁直观:
修改后的代码如下:
sma = go.Scatter( x=dfIbFour.index, y=dfIbFour["sma"], name="SMA", line=dict(color="blue", dash="dot", width=4), customdata=dfIbFour, hovertemplate=( f"Date:%{{customdata[0]}}<br>" f"**BollSpr: %{{customdata[{bollSpreadCol}]:.2f}} | LowBollCum%: %{{customdata[34]:.2%}} | SMACum%: %{{customdata[36]:.2%}} | EMACum%: %{{customdata[39]:.2%}}<br> " ) )
关键说明:
- 使用f-string时,因为
hovertemplate本身需要保留%{customdata[...]}这种Plotly的模板语法,所以要把里面的{}转义成{{}},而我们要插入的变量bollSpreadCol则用正常的{bollSpreadCol}包裹。 - 也可以选择用
str.format()方法实现,写法如下:
hovertemplate_str = "Date:%{customdata[0]}<br>**BollSpr: %{customdata[{idx}]:.2f} | LowBollCum%: %{customdata[34]:.2%} | SMACum%: %{customdata[36]:.2%} | EMACum%: %{customdata[39]:.2%}<br> " sma = go.Scatter( x=dfIbFour.index, y=dfIbFour["sma"], name="SMA", line=dict(color="blue", dash="dot", width=4), customdata=dfIbFour, hovertemplate=hovertemplate_str.format(idx=bollSpreadCol) )
两种方法都能实现动态替换列索引,后续新增列时只要bollSpreadCol通过columns.get_loc()正确获取索引,就不用手动修改hovertemplate里的数字了。
内容的提问来源于stack exchange,提问作者aaaahhhhhh
相关产品推荐
相关产品推荐

