gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 23:12:59 26 4
gpt4 key购买 nike

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

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/

26 4 0