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

Plotly Express带误差棒的悬浮框数字格式设置问题

解决Plotly Express误差棒散点图悬浮框数值位数问题

问题原因

直接替换hovertemplate中的{y}会丢失误差棒信息,是因为原始模板包含误差相关变量(error_y.plus和error_y.minus),仅修改{y}会破坏原有模板结构,导致误差字段无法正常渲染。

解决方案

手动构建完整的hovertemplate,同时格式化y值、误差上限和下限的显示位数,全程不修改原始数据:

import plotly.express as px
import numpy as np

df = px.data.iris()
df = df[df["species"]=="setosa"]
df["sepal_length"] += np.pi/5
df["e_plus"] = df["sepal_width"]/10*np.pi/4
df["e_minus"] = df["sepal_width"]/4*np.pi/4

fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species",
                 error_y="e_plus", error_y_minus="e_minus")

# 自定义悬浮框模板,将所有数值格式化为3位有效数字
fig.data[0].hovertemplate = (
    "sepal_width: %{x:.3g}<br>"
    "sepal_length: %{y:.3g} +%{error_y.plus:.3g} -%{error_y.minus:.3g}<br>"
    "species: %{color}"
)

fig.show()

细节说明

  • :.3g表示保留3位有效数字,可根据需求调整格式,比如:.2f代表保留2位小数
  • 模板完整保留了原始悬浮框的所有信息(x值、y值、误差范围、物种分类),仅调整数值显示精度
  • 全程未对原始数据集做任何四舍五入或修改操作

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 19:48:27