ggplot2有一种简单的方法来包装注释文本吗?

Sky*_*ker 6 r ggplot2

我目前正在使用ggplot2和annotate函数,文档中的示例如下.我有限的宽度来注释未知长度的文本,并需要一种自动方式将其包装在一些x_startx_end值中.由于我不想更改字体大小,我还需要y根据引入的中断数量来移动值.有没有一种简单的方法来实现这一目标?

# install.packages(c("ggplot2"), dependencies = TRUE)
require(ggplot2)
p <- ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point()
p + annotate("text", x = 4, y = 25, label = "Some arbitrarily larger text")
Run Code Online (Sandbox Code Playgroud)

use*_*650 5

也许包中的splitTextGrob功能RGraphics可以提供帮助。这将根据绘图窗口的宽度包装文本。

library(RGraphics)
library(ggplot2)


p <- ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point()

grob1 <-  splitTextGrob("Some arbitrarily larger text")

p + annotation_custom(grob = grob1,  xmin = 3, xmax = 4, ymin = 25, ymax = 25) 
Run Code Online (Sandbox Code Playgroud)


Eri*_*ail 5

仅使用base和的替代解决方案ggplot2

根据您上面介绍的内容进行构建

# First a simple wrapper function (you can expand on this for you needs)
wrapper <- function(x, ...) paste(strwrap(x, ...), collapse = "\n")
# The a label
my_label <- "Some arbitrarily larger text"
# and finally your plot with the label
p + annotate("text", x = 4, y = 25, label = wrapper(my_label, width = 5))
Run Code Online (Sandbox Code Playgroud)


gle*_*ton 5

我使用类似于 Eric Fail 的 tidyverse stringr 解决方案,但不需要创建函数(Eric 的函数也不需要创建函数):

# use str_wrap to wrap long text from annotate
p + annotate(
  "text", x = 4, y = 25,
  label = stringr::str_wrap(
    "Some arbitrarily larger text",
     width = 20
  )
)
Run Code Online (Sandbox Code Playgroud)