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

问题描述 投票:3回答:1

我想找到一种方法来自动包装ggplot标题(或字幕或标题)以占用完整的绘图宽度然后换行。

previous question处理如何使用包装函数很好地包装代码,但您仍然必须手动指定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))

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

plot_width <- ???

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

我怎样才能做到这一点?

或者,还有更好的方法?

r ggplot2
1个回答
2
投票

您需要提取设备宽度(使用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))
© www.soinside.com 2019 - 2024. All rights reserved.