如何为Plotly图表中所有现有悬浮提示文本添加换行符
解决BERTopic生成Plotly图表悬浮提示文本换行问题
你当前的思路是对的,但问题出在换行分隔符的转义上——Plotly的悬浮提示(hovertext)支持HTML格式,直接用<br>标签就能实现换行,而你用了转义后的<br>,它会被当成普通文本显示,不会触发换行。
修正后的代码如下:
import textwrap from bertopic import BERTopic from umap import UMAP from sentence_transformers import SentenceTransformer docs = [ # 你的文档内容 ] model = SentenceTransformer('all-MiniLM-L6-v2') embeddings = model(docs) topic_model = BERTopic() topics, probs = topic_model.fit_transform(docs, embeddings) reduced_embeddings = UMAP(n_neighbors=10, n_components=2, min_dist=0.0, metric='cosine').fit_transform(embeddings) fig = topic_model.visualize_documents(docs, reduced_embeddings=reduced_embeddings, width=1920, height=1080) def wrap_text(text, delimiter='<br>', after=80): if text is None: return text # 先按指定宽度换行,再把换行符替换成HTML换行标签 return textwrap.fill(text, width=after).replace('\n', delimiter) # 遍历所有trace处理hovertext,避免只处理第一个trace的遗漏情况 for trace in fig.data: trace.hovertext = [wrap_text(text) for text in trace.hovertext] trace.hoverinfo = 'text' # 显示或保存图表 fig.show()
关键修正点:
- 把分隔符从
<br>改为<br>,让Plotly识别为HTML换行标签 - 遍历
fig.data中的所有trace,确保所有悬浮提示都被处理(BERTopic生成的图表通常只有一个trace,但这样更健壮)
这样修改后,悬浮提示文本就会在每80个字符处自动换行,解决过长问题。
内容的提问来源于stack exchange,提问作者timbmg
相关产品推荐
相关产品推荐

