如果标题字符串太长,如何适应strip.text.x.

时间:2012-10-01 12:36:10

标签: r ggplot2

数据框:x

Date          Duration  Test
1/1/2012      10        This is the first that took place on1/1/2012
2/1/2012      3         This test peformed the best result

我正在寻找适合图表的strip.text.x的挑战。有没有人有任何建议如何解决这个问题?

ggplot(x, aes(Date, Duration, group=Test, colour=Test)) 
+ geom_line() 
+ geom_smooth(method="lm", se=T, size=1) 
+ facet_wrap(~Test, scale="free") 
+ opts(strip.text.x = theme_text(size=8, colour="navyblue"))

2 个答案:

答案 0 :(得分:2)

如果您可以使用facet_grid而不是facet_wrap,则可以使用labeller参数的功能来任意包装文本。 (facet_wrap没有(yet)有labeller参数。)

使x可重现

x <-
structure(list(Date = structure(c(-719143, -718778), class = "Date"), 
    Duration = c(10L, 3L), Test = c("This is the first that took place on1/1/2012", 
    "This test peformed the best result")), .Names = c("Date", 
"Duration", "Test"), row.names = c(NA, -2L), class = "data.frame")

帮助函数来包装标签(更详细地讨论on the ggplot2 wiki

library("plyr")
label_wrap_gen <- function(width = 25) {
    function(variable, value) {
      laply(strwrap(as.character(value), width=width, simplify=FALSE), 
            paste, collapse="\n")
    }
}

绘制代码。更改为点,因为只给出了两个值,因此线条和平滑没有意义。但无论如何,这些都不是问题的焦点。

ggplot(x, aes(Date, Duration, group=Test, colour=Test)) + 
  geom_point() +
  facet_grid(~Test, scale="free", labeller=label_wrap_gen(width=10)) + 
  opts(strip.text.x = theme_text(size=8, colour="navyblue"))

enter image description here

编辑:

由于facet_grid不适合您,您可以直接将换行符嵌入Test变量,然后使用facet_wrap

x$Test <- laply(strwrap(as.character(x$Test), width=10, simplify=FALSE), 
                paste, collapse="\n")
ggplot(x, aes(Date, Duration, group=Test, colour=Test)) + 
  geom_point() +
  facet_wrap(~Test, scale="free") + 
  opts(strip.text.x = theme_text(size=8, colour="navyblue"))

enter image description here

我不明白你在评论中提出的关于标题的其他问题。或许可以提出一个更清晰的新问题。

答案 1 :(得分:0)

现在在ggplot2::label_wrap_gen中可用。