ggplot2:将 facet/strip 文本分成两行 [英] ggplot2: Splitting facet/strip text into two lines

查看:31
本文介绍了ggplot2:将 facet/strip 文本分成两行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑下面的 ggplot2 图形,其中包含很长的 facet/strip 文本分成两行.文本超出了专用于方面标题的区域.

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)
x <- c(1:3, 1:3)
y <- c(3:1, 1:3)
grp <- c(0, 0, 0, 1, 1, 1)
p <- qplot(x=x, y=y) + geom_line() + facet_wrap(~ grp)
grob <- ggplotGrob(p)
strip.elem.y <- grid.ls(getGrob(grob, "strip.text.x", 
                grep=TRUE, global=TRUE))$name
grob <- geditGrob(grob, strip.elem.y[1], 
        label="First line and
 second line" )
grid.draw(grob)

有没有办法增加条形文本区域的高度?

Is there a way to increase the height of the strip text area ?

推荐答案

我尝试了多种方法,但对 paste(strwrap(text, width=40), collapse=" ") 感到沮丧 为我提供单行数据的结果,而不是连接整个列表中的每一位文本.

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

我想出了一个最适合我的解决方案.我写了一个像下面这样的函数.给定一个带有 text

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=" 
 ")
  return(wtext)
}

data$wrapped_text <- llply(data$text, wrapit)
data$wrapped_text <- unlist(data$wrapped_text)

在调用此函数后,我只是将 labeller 函数应用于 wrapped_text 列而不是 text 列.

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

这篇关于ggplot2:将 facet/strip 文本分成两行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆