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

Plotly堆叠条形图悬停信息文字不可读,如何修改其背景或文字颜色?

解决Plotly堆叠条形图悬停信息可读性问题

没问题,这个问题很好解决!Plotly完全支持自定义悬停标签(hoverlabel)的背景色、文字颜色甚至字体样式,刚好能解决你遇到的文字与背景色过于接近导致看不清的问题。

你可以通过两种方式调整悬停标签样式:

1. 全局统一设置所有系列的悬停标签

直接在Layout中添加hoverlabel配置项,一次性修改所有trace的悬停样式,适合需要统一风格的场景:

import plotly.graph_objects as go
trace0 = dict(
    x=list(range(24)),
    y=[163, 154, 114, 61, 32, 19, 20, 20, 26, 38, 67, 102, 132, 159],
    name="Two",
    type="bar",
    marker={"color": "rgba(81, 133, 198, 0.3)", "line": {"width": 0}},
)
trace1 = dict(
    x=list(range(24)),
    y=[0, 0, 0, 4, 19, 37, 49, 49, 39, 25, 7, 1, 0, 0],
    name="One",
    type="bar",
    marker={"color": "rgba(240, 240, 240, 1.0)", "line": {"width": 0}},
)
data = [trace0, trace1]
layout = go.Layout(
    paper_bgcolor="rgba(0,0,0,0)",
    plot_bgcolor="rgba(0,0,0,0)",
    hovermode="x",
    # 新增:全局悬停标签样式配置
    hoverlabel=dict(
        bgcolor="rgba(255, 255, 255, 0.9)",  # 半透明白色背景,避免遮挡图表
        font=dict(
            color="#333333",  # 深灰色文字,保证高对比度
            size=12
        ),
        bordercolor="#666666"  # 可选:给标签加细边框,增强区分度
    )
)
go.Figure(data=data, layout=layout).update_layout(barmode="stack")

2. 单独设置某个系列的悬停标签

如果希望不同系列的悬停标签和对应条形颜色呼应,可以在单个trace中添加hoverlabel配置:

比如给"Two"系列设置和条形同色系的背景+白色文字:

trace0 = dict(
    x=list(range(24)),
    y=[163, 154, 114, 61, 32, 19, 20, 20, 26, 38, 67, 102, 132, 159],
    name="Two",
    type="bar",
    marker={"color": "rgba(81, 133, 198, 0.3)", "line": {"width": 0}},
    # 单独设置该系列的悬停标签
    hoverlabel=dict(
        bgcolor="rgba(81, 133, 198, 0.8)",
        font=dict(color="white")
    )
)

这样调整后,悬停信息的对比度会大幅提升,文字就能清晰辨认了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 07:27:10