r - 格式化工具提示以用于长文本标签

标签 r ggplot2 plotly ggplotly

考虑下面的简单示例。有没有办法格式化绘图工具提示,以便长文本标签在框中可见,而不是这个切断值的荒谬矩形?

library(ggplot2); library(plotly)

df <- data.frame(x = 1:10, y = 1:10, z = rep("the longggggggggggggggggggggggggggggestttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttt labelllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllll you can imagineeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", 10))

p <- ggplot(df, aes(x,y,label=z)) + geom_point()
ggplotly(p, tooltip = "label")

enter image description here

最佳答案

我很确定,某个地方存在更优雅的解决方案。我只能建议你像每个人一样休息一下 n特点。来自 https://stackoverflow.com/a/2352006/9300556 的一个很好的解决方法:

gsub('(.{1,90})(\\s|$)', '\\1\n', s)

It will break string "s" into lines with maximum 90 chars (excluding the line break character "\n", but including inter-word spaces), unless there is a word itself exceeding 90 chars, then that word itself will occupy a whole line.



所以我们只需要添加 gsub()进入 ggplot美学:
p <- ggplot(df, aes(x,y,
            text = gsub('(.{1,20})(\\s|$)', '\\1\n', z))) +
  geom_point()

ggplotly(p, tooltip = "text")

enter image description here

更新

这是@Rich Pauloo 评论中的一个更优雅的解决方案。在这种情况下,您的字符串也将大部分被左填充(但实际上是自动对齐的)。但是,填充取决于绘图分辨率和标签位置。
library(stringr)

p <- ggplot(df,
            aes(x, y,
                text = stringr::str_wrap(
                  string = z,
                  width = 20,
                  indent = 1, # let's add extra space from the margins
                  exdent = 1  # let's add extra space from the margins
                ))) +
  geom_point()

ggplotly(p, tooltip = "text")

enter image description here

关于r - 格式化工具提示以用于长文本标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55643887/

相关文章:

r - 从 ggplot2 对象中提取使用过的比例

r - 为什么 coord_proj 和 ggplot2 给我这个错误?

python - 如何将分组的条形图拆分为子组?

r - 在 R 中:将列名作为参数传递,并在 dplyr::mutate() 和 lazyeval::interp() 的函数中使用它

r - 如何按每个子列表的最大值对列表进行排序?

r - 将世界地图分为特定国家/地区的面板

r - 使用 gganimate 动画 geom_bar 的问题

R 绘图扩展跟踪 : Change to incremental and clear data

根据与输入 df 的逻辑比较返回子集

r - GenomicRanges 增加覆盖范围