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

如何在Plotly中对齐Hovertemplate第二列?空格方式无法满足需求

Plotly Hovertemplate 第二列对齐解决方案

直接添加普通空格无法实现理想对齐,因为Plotly悬浮提示使用比例字体,不同字符(包括空格)宽度不一致,手动补空格的方式会失效。推荐两种可靠的解决方法:

方法一:使用HTML固定宽度空格

用HTML固定宽度空格实体(如 全角空格、 半角空格)替代普通空格,这类空格宽度固定,能精准控制对齐。示例修改如下:

import plotly.express as px
import pandas as pd
import numpy as np

r = np.random.RandomState(42)
df = pd.DataFrame(
    {
        **{"x": np.linspace(0, 1, 10), "y": r.uniform(8, 9, 10)},
        **{c: r.uniform(i, i + 1, 10) for i, c in enumerate("ABCDE")},
    }
)

fig = px.scatter(df, x="x", y="y", hover_data={c: True for c in df.columns})

fig.update_traces(
    hovertemplate="<br>".join(
        [
            "<b>TT:</b>&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;%{customdata[0]}",
            "<b>A:</b>&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;%{x:.3f} deg",
            "<b>CCCCC:</b>&emsp;&emsp;&emsp;&emsp;&emsp;%{y:.3f} deg",
            "<b>K:</b>&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;%{customdata[2]:.3f} deg",
            "<b>LLLLLLLLLLLLLL:</b>&emsp;%{customdata[1]:.3f} deg<extra></extra>",
        ]
    )
)

fig.show()

方法二:使用HTML表格(推荐)

利用HTML表格的天然列对齐特性,这是最稳定且易维护的方案,无需手动调整空格数量:

import plotly.express as px
import pandas as pd
import numpy as np

r = np.random.RandomState(42)
df = pd.DataFrame(
    {
        **{"x": np.linspace(0, 1, 10), "y": r.uniform(8, 9, 10)},
        **{c: r.uniform(i, i + 1, 10) for i, c in enumerate("ABCDE")},
    }
)

fig = px.scatter(df, x="x", y="y", hover_data={c: True for c in df.columns})

fig.update_traces(
    hovertemplate="""
    <table>
      <tr><td><b>TT:</b></td><td>%{customdata[0]}</td></tr>
      <tr><td><b>A:</b></td><td>%{x:.3f} deg</td></tr>
      <tr><td><b>CCCCC:</b></td><td>%{y:.3f} deg</td></tr>
      <tr><td><b>K:</b></td><td>%{customdata[2]:.3f} deg</td></tr>
      <tr><td><b>LLLLLLLLLLLLLL:</b></td><td>%{customdata[1]:.3f} deg</td></tr>
    </table><extra></extra>
    """
)

fig.show()

若需要调整第二列对齐方式,可通过style属性修改,比如<td style="text-align:right">实现右对齐,无论左侧标签长度如何变化,都能保持整齐的列布局。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 11:50:30