如何自定义Plotly县级填充地图的悬浮提示文本?
自定义Plotly县级填充地图的悬浮提示文本
当然可以完全自定义鼠标悬浮时的提示内容!Plotly的create_choropleth函数提供了灵活的参数,能轻松实现你想要的格式——只显示县名称和指定属性,还能自由调整换行、样式。
具体实现步骤
- 准备好包含所需字段的数据:确保你的数据框里有
County、Attribute1、Attribute2这些你想展示的字段,同时保留FIPS和Value(这两个是创建填充地图的必需字段)。 - 传递自定义字段并配置提示模板:通过
custom_data把需要的字段传给函数,再用hovertemplate编写你想要的提示格式。
代码示例
import plotly.figure_factory as ff import pandas as pd # 替换成你自己的真实数据集 df = pd.DataFrame({ 'FIPS': ['42129', '42001', '42003'], 'County': ['Westmoreland', 'Allegheny', 'Armstrong'], 'Value': [100, 200, 150], 'Attribute1': ['Val1', 'Val2', 'Val3'], 'Attribute2': ['ValA', 'ValB', 'ValC'] }) # 创建带自定义悬浮提示的填充地图 fig = ff.create_choropleth( fips=df['FIPS'], values=df['Value'], scope=['Pennsylvania'], # 替换成你要展示的州/区域 custom_data=[df['County'], df['Attribute1'], df['Attribute2']], # 自定义提示模板:<br>实现换行,<b>给县名加粗,<extra></extra>隐藏默认冗余信息 hovertemplate='<b>County : %{customdata[0]}</b><br>' + 'Attribute 1 : %{customdata[1]}<br>' + 'Attribute 2 : %{customdata[2]}<extra></extra>' ) fig.show()
关键说明
custom_data:按顺序传入你想在提示里显示的字段,后续在hovertemplate中用%{customdata[索引]}引用对应的值。hovertemplate:完全自定义文本格式,<br>实现换行,<b>...</b>可以给重要内容(比如县名)加粗,<extra></extra>用来隐藏Plotly默认的trace名称提示,让界面更干净。- 如果需要更个性化的样式(比如颜色、字体大小),还可以在模板里加入HTML样式标签,比如
<span style="color:darkgreen;font-size:14px">...</span>。
内容的提问来源于stack exchange,提问作者Rahulcs75
相关产品推荐
相关产品推荐

