21

考虑下面的 ggplot2 图表,其中长的 facet/strip 文本分成两行。文本超出了专门用于构面标题的区域。

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)

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

4

3 回答 3

47

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))
于 2017-08-30T21:45:08.823 回答
17

您可以使用 2 行标签:

grp <- c(rep("foo\nbar",3), 1, 1, 1)
qplot(x=x, y=y) + geom_line() + facet_wrap(~ grp)
于 2012-01-29T11:06:27.220 回答
8

我尝试了多种方法,但很沮丧让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列。

于 2012-12-09T04:24:49.880 回答