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

如何在R的Plotly中修改hovertext悬浮框尺寸

问题

使用R语言结合Plotly绘制柱状图时,将长字符串coiids设置为hovertext,但悬浮框因屏幕宽度限制导致内容被截断。现有数据及绘图代码如下:

数据

my_data <-
  structure(
    list(
      flood_freq = "none",
      count = 111L,
      acres = 213698L,
      coiids = "632879, 632880, 633192, 633643, 633647, 634220, 634252, 2517005, 2517018, 2630129, 2630149, 2630150, 635379, 632879, 632880, 2517005, 635629, 635631, 2517005, 2517018, 2630129, 2630149, 2630150, 2630203, 2630207, 2630215, 2528971, 2406001, 2719494, 2719503, 2719504, 634220, 2517005, 2517018, 2630149, 2630150, 1423710, 2630203, 2630207, 1472815, 1472823, 2630215, 2528971, 2630207, 2406001, 635796, 635797, 635798, 635799, 635803, 635804, 635862, 635864, 635865, 635867, 635868, 635870, 635871, 635917, 635947, 635948, 635949, 635950, 635984, 635985, 635986, 635987, 635988, 635989, 635990, 635997, 636005, 636008, 636095, 636097, 636099, 636119, 636120, 636121, 637182, 637183, 637184, 637196, 637230, 637232, 637259, 637260, 637473, 637475, 637477, 637479, 2719494, 2719503, 2719504, 637647, 637649, 637652, 637657, 637667, 637821, 637944, 637945, 637946, 637947, 637949, 638073, 638160, 638161, 638216, 638217, 638218"
    ),
    class = c("tbl_df",  "tbl", "data.frame"),
    row.names = c(NA, -1L)
  ) 

原始绘图代码

plotly::plot_ly(
  x = my_data$flood_freq,
  y = my_data$count,
  name = "Flood freq.",
  type = "bar",
  hoverinfo = "text",
  hovertext = paste("coiids: ", my_data$coiids)
)

需求:修改hovertext悬浮框的尺寸,设置固定宽度并增加高度,以完整显示所有coiids内容。


解决方案

可以通过两种方式解决该问题:

方法1:拆分长字符串+设置悬浮框固定宽度

将coiids中的逗号替换为带换行的分隔符,让内容自动换行,同时通过hoverlabel参数设置固定宽度,Plotly会自动适配悬浮框高度:

# 格式化coiids字符串,添加换行符
formatted_coiids <- gsub(", ", ",\n", my_data$coiids)

plotly::plot_ly(
  x = my_data$flood_freq,
  y = my_data$count,
  name = "Flood freq.",
  type = "bar",
  hoverinfo = "text",
  hovertext = paste("coiids:\n", formatted_coiids)
) %>%
  plotly::layout(
    hoverlabel = list(
      bgcolor = "white",
      bordercolor = "black",
      # 设置固定宽度(单位:像素)
      width = 400
    )
  )

方法2:自定义CSS控制悬浮框样式(带滚动条)

如果内容过长不想让悬浮框高度过高,可以添加自定义CSS,设置最大宽度、最大高度并启用垂直滚动:

library(htmlwidgets)

plotly::plot_ly(
  x = my_data$flood_freq,
  y = my_data$count,
  name = "Flood freq.",
  type = "bar",
  hoverinfo = "text",
  hovertext = paste("coiids: ", my_data$coiids)
) %>%
  onRender("
    function(el) {
      el.on('plotly_hover', function() {
        var hoverLabels = document.querySelectorAll('.hovertext');
        hoverLabels.forEach(function(label) {
          label.style.maxWidth = '400px';
          label.style.maxHeight = '300px';
          label.style.overflowY = 'auto';
        });
      });
    }
  ")

说明

  • 方法1操作简单,适合希望内容完全展开显示的场景;
  • 方法2适合内容超长的情况,通过滚动条控制悬浮框高度,避免影响页面布局。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 15:00:46