包装 ggplot2 文本以适合绘图宽度

cap*_*ain 4 r ggplot2

我想找到一种方法来自动包装 ggplot 标题(或副标题或标题)以占据整个绘图宽度然后换行。

一个先前的问题与如何很好地使用包装函数来包装的代码,但你仍然有交易指定width=手动。如何重写此包装函数以根据绘图的绘图宽度自动包装文本?

到目前为止我的代码:

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

library("ggplot2")

my_title <- "This is a really long title of a plot that I want to nicely wrap and fit the plot width without having to manually add the backslash n, or having to specify with= manually"

ggplot(data = cars, aes(x = speed, y = dist)) +    
  geom_smooth() +   
  labs(title = wrapper(my_title, width = 100))
Run Code Online (Sandbox Code Playgroud)

我的想法:以某种方式从 ggplot 中提取绘图宽度,然后将其包含在包装函数中,可能是这样的:

plot_width <- ???

wrapper <- function(x)  {   
  paste(strwrap(x, width = plot_width), collapse = "\n") 
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

或者,还有更好的方法?

PoG*_*bas 6

您需要提取设备宽度(使用dev.size函数)。您可以使用wrapper其中参数dev_width是当前设备宽度的函数来完成。但是,您可能仍然需要调整宽度以strwrap使用dev_scaler参数(大约 12 左右的值对我来说大部分时间都有效)。

#' @param label character string to wrap
#' @param dev_width numeric value specifying width of current device
#' @param dev_scaler numeric value to scale dev_width (might be around ~12)
#' 
wrapper <- function(label, dev_width = dev.size("in")[1], dev_scaler = 12)  {   
  paste(strwrap(label, dev_width * dev_scaler), collapse = "\n") 
}

ggplot(data = cars, aes(x = speed, y = dist)) +    
  geom_smooth() +   
  labs(title = wrapper(my_title))
Run Code Online (Sandbox Code Playgroud)