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

Plotly px.histogram自定义悬浮提示异常问题求助

解决Plotly Express Histogram悬浮提示自定义问题

问题说明

使用px.histogram绘制分组柱状图时,悬浮提示默认显示sum of Dolares,尝试通过labels参数修改无效,使用update_traces设置hovertemplate也未达到预期效果,需要自定义悬浮提示为:包含Periodo、重命名后的Uso(原Usos字段)、带$前缀的Dolares数值。

核心原因

  1. px.histogram默认对y轴字段执行sum聚合操作,因此悬浮提示会自动添加sum of前缀;
  2. labels参数仅映射原始字段名,无法直接修改聚合后的显示文本;
  3. 之前的hovertemplate中%{color}引用错误,color是分组标识,并非可直接读取的字段值。

解决方案

提供两种可行方法,均能实现自定义悬浮提示的需求:

方法一:利用Trace的Name值

因为color="Periodo"分组后,每个trace的name对应Periodo的具体值,可直接在hovertemplate中引用:

import pandas as pd
import plotly.express as px

df_grafico2 = pd.DataFrame(data = {
    "Usos" : ['Total','BK','BI','CyL','PyA','BC','VA','Resto','Total','BK','BI','CyL','PyA','BC','VA','Resto'],
    "Periodo" : ['Octubre 2021*','Octubre 2021*','Octubre 2021*','Octubre 2021*','Octubre 2021*','Octubre 2021*','Octubre 2021*','Octubre 2021*','Octubre 2022*','Octubre 2022*','Octubre 2022*','Octubre 2022*','Octubre 2022*','Octubre 2022*','Octubre 2022*','Octubre 2022*'],
    "Dolares" : [5247,869,2227,393,991,606,104,57,6074,996,2334,601,1231,676,202,33]
    })

# 绘制分组柱状图,显式指定聚合方式,设置字段重命名
plot_impo_usos = px.histogram(
    df_grafico2[df_grafico2.Usos != "Total"], 
    x = "Usos", 
    y = "Dolares",
    color="Periodo", 
    barmode="group", 
    template="none",
    histfunc='sum',
    labels={"Usos": "Uso", "Dolares": "Dólares"},
    hover_data=["Periodo", "Dolares"]
)

# 修改y轴格式与标题
plot_impo_usos.update_yaxes(tickformat = ",", title_text='En millones de USD')

# 自定义悬浮提示模板,%{name}获取Periodo值,%{y:,.0f}格式化数值
plot_impo_usos.update_traces(
    hovertemplate='Periodo: %{name}<br>Uso: %{x}<br>Dólares: $%{y:,.0f}'
)

# 更新布局样式
plot_impo_usos.update_layout(
    separators=",.",
    font_family='georgia', 
    title_text = "Importación por usos económicos. Octubre de 2022 y octubre de 2021",
    legend=dict(
        yanchor="top", 
        orientation = "h",
        y=1.07,
        xanchor="left",
        x=0.3
    )
)

plot_impo_usos.show()

方法二:使用Custom Data传递字段

通过custom_data传递Periodo字段,在hovertemplate中引用自定义数据数组:

import pandas as pd
import plotly.express as px

df_grafico2 = pd.DataFrame(data = {
    "Usos" : ['Total','BK','BI','CyL','PyA','BC','VA','Resto','Total','BK','BI','CyL','PyA','BC','VA','Resto'],
    "Periodo" : ['Octubre 2021*','Octubre 2021*','Octubre 2021*','Octubre 2021*','Octubre 2021*','Octubre 2021*','Octubre 2021*','Octubre 2021*','Octubre 2022*','Octubre 2022*','Octubre 2022*','Octubre 2022*','Octubre 2022*','Octubre 2022*','Octubre 2022*','Octubre 2022*'],
    "Dolares" : [5247,869,2227,393,991,606,104,57,6074,996,2334,601,1231,676,202,33]
    })

plot_impo_usos = px.histogram(
    df_grafico2[df_grafico2.Usos != "Total"], 
    x = "Usos", 
    y = "Dolares",
    color="Periodo", 
    barmode="group", 
    template="none",
    histfunc='sum',
    labels={"Usos": "Uso", "Dolares": "Dólares"},
    custom_data=["Periodo"]  # 传递自定义字段
)

plot_impo_usos.update_yaxes(tickformat = ",", title_text='En millones de USD')

# 通过customdata[0]获取Periodo值
plot_impo_usos.update_traces(
    hovertemplate='Periodo: %{customdata[0]}<br>Uso: %{x}<br>Dólares: $%{y:,.0f}'
)

plot_impo_usos.update_layout(
    separators=",.",
    font_family='georgia', 
    title_text = "Importación por usos económicos. Octubre de 2022 y octubre de 2021",
    legend=dict(
        yanchor="top", 
        orientation = "h",
        y=1.07,
        xanchor="left",
        x=0.3
    )
)

plot_impo_usos.show()

补充说明

  • %{y:,.0f}用于格式化数值,添加千位分隔符并显示为整数;
  • labels参数负责统一图表轴标签、图例等区域的文本命名;
  • 两种方法均可实现需求,方法一更简洁高效。

内容的提问来源于stack exchange,提问作者Keynes is not dead

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 15:05:14