ggplot2: Splitting facet/strip text into two lines

前端 未结 3 1800
-上瘾入骨i
-上瘾入骨i 2020-12-03 07:30

Consider the following ggplot2 graph with long facet/strip text broken in two lines. The text goes outside the area devoted to facet titles.

library(ggplot2         


        
相关标签:
3条回答
  • 2020-12-03 08:06

    You can use a 2-line label:

    grp <- c(rep("foo\nbar",3), 1, 1, 1)
    qplot(x=x, y=y) + geom_line() + facet_wrap(~ grp)
    
    0 讨论(0)
  • 2020-12-03 08:10

    ggplot2 supports a built in way of doing this using label_wrap_gen.

    x <- c(1:3, 1:3)
    y <- c(3:1, 1:3)
    grp = c(rep("group 1 with a long name",3),rep("group 2 with a long name",3))
    d = data.frame(x = x, y =y, grp = grp)
    ggplot(d, aes(x=x,y=y)) + geom_line() + facet_wrap(~ grp, labeller = label_wrap_gen(width=10))
    
    0 讨论(0)
  • 2020-12-03 08:23

    I tried this a variety of ways but was frustrated getting the paste(strwrap(text, width=40), collapse=" \n") to give me results for the single row of data and not concatenate the each bit of text from the entire list.

    I came up with a solution that worked best for me. I wrote a function like the one below. Given a dataframe data with column text

    wrapit <- function(text) {
      wtext <- paste(strwrap(text,width=40),collapse=" \n ")
      return(wtext)
    }
    
    data$wrapped_text <- llply(data$text, wrapit)
    data$wrapped_text <- unlist(data$wrapped_text)
    

    After I called this function, I just applied my labeller function to the wrapped_text column instead of the text column.

    0 讨论(0)
提交回复
热议问题