包装长 geom_text 标签

Ale*_*der 6 r ggplot2

我在 ggplot2 中包装长文本时遇到问题。类似的问题在这里问GGPLOT2有没有一种简单的方法来包装注释文本?

我的问题是我们是否有这样的文字

my_label <- "Some_arbitrarily_larger_text"
Run Code Online (Sandbox Code Playgroud)

我们如何使用相同的方法缩小它?

wrapper <- function(x, ...) paste(strwrap(x, ...), collapse = "\n")

library(ggplot2)
ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point()+
annotate("text", x = 4, y = 25, label = wrapper(my_label, width = 5))
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

它似乎不适用于这种情况!

eda*_*aja 10

您也可以调用stringr::str_wrap(),用于:

library(ggplot2)
ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point()+
  annotate("text", x = 4, y = 25, label = stringr::str_wrap(my_label, 5))
Run Code Online (Sandbox Code Playgroud)

不过,如果这就是您要查找的内容,我认为其中任何一个都不会分解一个词。


hrb*_*str 6

使用 Unicode 零宽度空格并将所有_\ 替换为_+ it:

\n\n
library(stringi)\nlibrary(ggplot2)\n\nmy_label <- "Some_arbitrarily_larger_text"\nmy_label <- stri_replace_all_fixed(my_label, "_", "_\\U200B")\n
Run Code Online (Sandbox Code Playgroud)\n\n

肉眼看来它是连续的:

\n\n
my_label\n## [1] "Some_\xe2\x80\x8barbitrarily_\xe2\x80\x8blarger_\xe2\x80\x8btext"\n
Run Code Online (Sandbox Code Playgroud)\n\n

但是,从编程上来说,这是一个断字/换行的机会:

\n\n
wrapper <- function(x, ...) paste(stri_wrap(x, ...), collapse = "\\n")\n\nggplot(mtcars, aes(x = wt, y = mpg)) + \n  geom_point() +\n  annotate("text", x = 4, y = 25, label = wrapper(my_label, width = 5))\n
Run Code Online (Sandbox Code Playgroud)\n\n

在此输入图像描述

\n