情节标题的文字换行

Dom*_*bey 42 plot r

我对R中的情节有很长的标题,并且它一直延伸到情节窗口之外.如何将标题包装成2行?

JD *_*ong 51

尝试在标题中间添加"\n"(新行).例如:

plot(rnorm(100), main="this is my title \non two lines")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • @gagarine 期待在不久的将来为您更好的答案投票! (2认同)

Gre*_*now 41

您可以使用该strwrap函数将长字符串拆分为多个字符串,然后使用pastewith collapse=\n来创建要传递给主标题参数的字符串.您可能还希望使用parmar参数的函数为边缘留出更多空间.

  • 动态生成字符串的唯一解决方案. (6认同)
  • 上面作为一个可以应用于字符串向量的函数:`wrap_strings < - function(vector_of_strings,width){sapply(vector_of_strings,FUN = function(x){paste(strwrap(x,width = width),collapse = "\n")})}` (4认同)

Dir*_*tel 7

通过添加换行符:

plot(1:10, main=paste(rep("The quick brown fox", 3), sep="\n"))
Run Code Online (Sandbox Code Playgroud)

这将创建一个具有三条(相同)线条的图块.只需\n在你的子串之间使用.


Rei*_*son 7

\n在标题字符串中包含换行符/换行符(\n ),例如:

strn <- "This is a silly and overly long\ntitle that I want to use on my plot"
plot(1:10, main = strn)
Run Code Online (Sandbox Code Playgroud)

  • 您不必添加换行符来换行文本。这应该是自动的...我必须生成大约 100 个图表,我不想手动拆分每个标题。 (2认同)

gag*_*ine 7

您可以使用strwrappaste自动换行图表的标题。宽度需要适应您的介质宽度。

plot(rnorm(100), main = paste(
  strwrap(
    'This is a very long title wrapped on multiple lines without the need to adjust it by hand',
    whitespace_only = TRUE,
    width = 50
  ),
  collapse = "\n"
))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

R 应该自动执行此操作,没有人想要裁剪标题。


Ric*_*kyB 5

这可能对任何句子都有用,因此它可以根据单词进行拆分:

wrap_sentence <- function(string, width) {
  words <- unlist(strsplit(string, " "))
  fullsentence <- ""
  checklen <- ""
  for(i in 1:length(words)) {
    checklen <- paste(checklen, words[i])
    if(nchar(checklen)>(width+1)) {
      fullsentence <- paste0(fullsentence, "\n")
      checklen <- ""
    }
    fullsentence <- paste(fullsentence, words[i])
  }
  fullsentence <- sub("^\\s", "", fullsentence)
  fullsentence <- gsub("\n ", "\n", fullsentence)
  return(fullsentence)
}
Run Code Online (Sandbox Code Playgroud)

我确信有一种更有效的方法可以做到这一点,但它确实可以完成这项工作。