如何将Plotly工具提示背景色设置为与悬停像素颜色一致?
实现Plotly图像悬停工具提示背景色与像素颜色一致
你可以借助Plotly的hovertemplate支持HTML语法的特性,通过内联样式直接设置工具提示的背景色,让它和当前悬停像素的颜色完全匹配。具体实现方式如下:
修改后的完整代码
import numpy as np import plotly.graph_objects as go size = 5 img = np.random.random((size, size, 3)) * 255 fig = go.Figure( go.Image( z=img, customdata=img.astype(int), # 通过HTML内联样式设置背景色,同时优化文字可读性 hovertemplate='<div style="background-color: rgb(%{customdata[0]},%{customdata[1]},%{customdata[2]}); padding: 8px; color: %{text};">' '<br>R: %{customdata[0]}' '<br>G: %{customdata[1]}' '<br>B: %{customdata[2]}' '</div>', # 根据像素亮度自动切换文字颜色,避免背景色过深/过浅时文字看不清 text=['white' if (r*0.299 + g*0.587 + b*0.114) < 128 else 'black' for r,g,b in img.reshape(-1,3)], name='' ) ) fig.show('browser')
核心细节说明
- 直接用
rgb(%{customdata[0]},%{customdata[1]},%{customdata[2]})将悬停像素的RGB值映射为工具提示的背景色,实现颜色同步。 - 新增
text参数结合亮度计算公式,自动判断文字用白色还是黑色,保证在任何背景色下内容都清晰可读。 - 给包裹内容的
<div>添加padding样式,让工具提示的布局更美观。
内容的提问来源于stack exchange,提问作者leleogere
相关产品推荐
相关产品推荐

