ggplot2:将facet / strip文本拆分为两行

时间:2012-01-29 10:59:20

标签: r graph ggplot2 facet-wrap

考虑以下带有长小平面/条带文本的ggplot2图形 分成两行。 该文本超出了专门用于标题的区域。

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\n second line" )
grid.draw(grob)

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

3 个答案:

答案 0 :(得分:15)

您可以使用2行标签:

grp <- c(rep("foo\nbar",3), 1, 1, 1)
qplot(x=x, y=y) + geom_line() + facet_wrap(~ grp)

答案 1 :(得分:11)

ggplot2支持使用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))

答案 2 :(得分:6)

我尝试了各种各样的方法,但是让paste(strwrap(text, width=40), collapse=" \n")给我单行数据的结果并且没有连接整个列表中的每一位文本感到很沮丧。

我想出了一个最适合我的解决方案。我写了一个类似下面的函数。给定数据框data,列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)

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

相关问题