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

如何在ggplotly提示框中实现文本左对齐、数值右对齐

解决方案

核心需求(提示框标签左对齐、数值右对齐)实现方法

Plotly的hoverlabel.align是全局配置,无法针对同一条提示框内的不同文本分别设置对齐,你可以利用Plotly支持HTML标签渲染提示框内容的特性,用HTML表格实现分栏对齐。

修改后的完整代码如下:

library(ggplot2)
library(plotly)

sales <- data.frame(names = c("Joey","Adam","Paul"),
                    expenses = c(10056.244,17621.901,13090.782),
                    revenue = c(20161252367.729,1922363266239.341,24091234670.048))

p <- ggplot(sales, aes(x = expenses, y = revenue)) +
  geom_point(aes(text = paste0(
    # 无边距表格控制分栏对齐
    "<table style='border-collapse:collapse;'>",
    "<tr>",
    "<td align='left' style='padding-right:12px;'>Expenses:</td>",
    "<td align='right'>$", format(round(expenses,2), nsmall = 1, big.mark = ","), "</td>",
    "</tr>",
    "<tr>",
    "<td align='left' style='padding-right:12px;'>Revenue:</td>",
    "<td align='right'>$", format(round(revenue,2), nsmall = 1, big.mark = ","), "</td>",
    "</tr>",
    "</table>"
  ))) +
  stat_smooth(method = "lm", level = 0.1,
              size = 0.25, color = "red")

ggplotly(tooltip = "text") %>% 
  layout(hoverlabel = list(bgcolor = "white"))

代码中的padding-right参数用于控制标签和数值之间的空隙,你可以根据显示需求调整数值大小。

额外需求(回归线添加悬停文本)实现方法

ggplot转换为plotly对象后,散点是第一个trace,回归线是第二个trace,直接用style()函数给第二个trace指定悬停文本即可,代码调整如下:

ggplotly(tooltip = "text") %>% 
  layout(hoverlabel = list(bgcolor = "white")) %>%
  # traces=2对应回归线图层,hoverinfo指定仅显示自定义文本
  style(hovertext = "线性拟合回归线 | 置信水平:90%", hoverinfo = "text", traces = 2)

如果需要显示回归线的具体参数(如斜率、截距),可以提前拟合模型提取对应数值,拼接进hovertext即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 10:57:02