Plotly Express散点图悬停数据格式丢失问题求助
Plotly散点图Hover数据格式丢失的原因与解决方法
问题描述
对数据集列进行数值预处理,格式化为带货币符号与千分位的字符串后,打印显示正常,但用于Plotly Express散点图并设置hover_data后,格式被剥离:LR丢失千分位逗号,LRC丢失美元符号。
预处理代码:
scatter_df["cost"] = "$" + scatter_df["cost"].apply(lambda x: "{:,.2f}".format(x)) scatter_df["LRC"] = "$" + scatter_df["LRC"].apply(lambda x: "{:,.2f}".format(x)) scatter_df["LR"] = scatter_df["LR"].apply(lambda x: "{:,}".format(x)) print(scatter_df) fig = px.scatter( scatter_df, x="LR", y="LRC", color="country", title="Reach to Cost", hover_data={ "cost": True, }, )
数据集示例:
| country | cost | LRC | LR |
|---|---|---|---|
| Afghanistan | $2,665.70 | $0.23 | 11,746 |
| Azerbaijan | $6,172.40 | $4.31 | 1,433 |
| Brazil | $7,084.11 | $0.44 | 16,083 |
| Georgia | $4,311.19 | $1.14 | 3,795 |
原因分析
Plotly Express会自动识别数据类型以适配绘图逻辑:
- 当你将数值列转换为带格式的字符串后,Plotly在处理x/y轴(
LR、LRC)时,会将这些字符串强制转换为数值类型(因为轴需要数值计算坐标),导致格式化的货币符号、千分位逗号被剥离。 hover_data中如果引用x/y轴对应的字段,Plotly会使用转换后的数值而非你预处理的字符串,因此格式丢失。
解决方法
方法1:保留原始数值,用Plotly内置格式化规则处理
不修改原始数值列,通过Plotly的tickformat设置轴显示格式,再用hovertemplate自定义hover内容格式,既保证绘图的数值准确性,又能保留格式化效果。
示例代码:
# 直接使用原始数值列绘图 fig = px.scatter( scatter_df, x="LR", y="LRC", color="country", title="Reach to Cost", hover_data=["cost"], ) # 设置x轴(LR)显示千分位格式 fig.update_xaxes(tickformat=",") # 设置y轴(LRC)显示美元符号+两位小数格式 fig.update_yaxes(tickformat="$,.2f") # 自定义hover模板,确保所有字段显示正确格式 fig.update_traces( hovertemplate="<b>Country:</b> %{customdata[0]}<br>" + "<b>LR:</b> %{x:,}<br>" + "<b>LRC:</b> $%{y:.2f}<br>" + "<b>Cost:</b> $%{customdata[1]:,.2f}<br>" + "<extra></extra>" )
方法2:保留格式化字符串列,分离绘图用数值列
复制原始数值列用于绘图,预处理后的字符串列仅用于hover显示,避免Plotly强制转换数据类型。
示例代码:
# 复制原始数值列,用于绘图计算坐标 scatter_df["LR_num"] = scatter_df["LR"].copy() scatter_df["LRC_num"] = scatter_df["LRC"].copy() # 生成格式化后的字符串列 scatter_df["cost"] = "$" + scatter_df["cost"].apply(lambda x: "{:,.2f}".format(x)) scatter_df["LRC_str"] = "$" + scatter_df["LRC"].apply(lambda x: "{:,.2f}".format(x)) scatter_df["LR_str"] = scatter_df["LR"].apply(lambda x: "{:,}".format(x)) # 绘图时用数值列作为x/y轴,hover用格式化后的字符串列 fig = px.scatter( scatter_df, x="LR_num", y="LRC_num", color="country", title="Reach to Cost", hover_data={ "LR_str": "LR", # 显示名称为LR,值用格式化后的字符串 "LRC_str": "LRC", "cost": True }, ) # 设置x/y轴显示格式与hover内容一致 fig.update_xaxes(tickformat=",") fig.update_yaxes(tickformat="$,.2f")
内容的提问来源于stack exchange,提问作者Jeff Oberlander
相关产品推荐
相关产品推荐

