You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在mpld3中实现支持多行内容显示的tooltip功能

解决方法

mpld3 默认的普通 tooltip 为纯文本渲染模式,会自动忽略换行符同时转义 HTML 标签,因此无法直接通过 \n 或 <br> 实现换行。你需要使用 mpld3 提供的 HTMLTooltip 插件来支持 HTML 格式的 tooltip 内容。


1. 修改标签生成逻辑

将原代码中用 \n 拼接的逻辑改为用 HTML 换行标签 <br> 拼接:

text = ('SEX: ' + str(ALL_CNMI['SEX'].loc[index]) + '<br>' + 'AGE: ' + str(ALL_CNMI['AGE'].loc[index]))
labels.append(text)

2. 绑定 HTMLTooltip 到图表

完整可运行示例如下:

import matplotlib.pyplot as plt
import mpld3
from mpld3 import plugins

# 此处替换为你自己的绘图数据
x = [1,2,3,4,5]
y = [2,4,1,5,3]
# labels 为上一步生成的带 <br> 标签的文本列表

fig, ax = plt.subplots()
scatter_points = ax.scatter(x, y)

# 绑定HTML格式的tooltip,voffset参数控制tooltip和鼠标的垂直偏移
tooltip = plugins.HTMLTooltip(scatter_points, labels=labels, voffset=10)
plugins.connect(fig, tooltip)

# 渲染查看效果,支持直接生成html文件或者在Jupyter notebook中显示
mpld3.show()

可选:自定义tooltip样式

可以通过传入CSS参数调整tooltip的显示效果,示例如下:

custom_css = """
.tooltip {
    background-color: #fff;
    border: 1px solid #999;
    padding: 6px 8px;
    border-radius: 4px;
    font-size: 14px;
    line-height: 1.5;
}
"""
tooltip = plugins.HTMLTooltip(scatter_points, labels=labels, voffset=10, css=custom_css)

最终渲染出来的tooltip会自动按照<br>标签换行,实现你需要的显示效果。


内容的提问来源于stack exchange,提问作者agon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 21:30:00