You need to enable JavaScript to run this app. Plotly堆叠面积图groupnorm='percent'时hoverlabel显示实际值而非百分比问题
优惠活动
大模型
产品
解决方案
定价
更多

Plotly堆叠面积图groupnorm='percent'时hoverlabel显示实际值而非百分比问题

解决方法

你设置groupnorm='percent'后,Plotly会自动将y轴数值转换为分组百分比,原始数值默认不会保存在trace的y字段中,因此直接读取%{y}只能拿到百分比值。

你可以通过custom_data参数将原始数值绑定到图表trace上,再在hover模板中调用绑定的原始值即可,修改后的可运行代码如下:

import pandas as pd
import plotly.express as px

df = pd.DataFrame({'date': list(pd.date_range(start='2021-01-01', periods=4, freq='D')) *3,
                   'value': [3,7,9,13,5,8,13,19,0,0,2,3],
                   'continent':['Asia'] * 4 + ['North America'] * 4 + ['Europe'] * 4})

# 新增custom_data参数,传入原始value字段进行绑定
fig = px.area(df, x='date', y='value', color='continent', groupnorm='percent', custom_data=['value'])
# hover模板从customdata中读取原始数值,也可根据需要保留百分比展示
fig.update_traces(hovertemplate='%{x}<br>%{fullData.name}: %{customdata[0]}<extra></extra>')
fig.update_layout(hovermode='x unified')
fig.show()

运行后hover时各大陆显示的就是对应的原始数值,比如2021-01-03的亚洲项显示9、北美显示13、欧洲显示2,完全符合需求。如果需要同时展示百分比,也可以在hovertemplate中添加%{y:.2f}%即可同时显示占比。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 03:24:10