如何将if语句参数传递给scale_y_continuous()?

时间:2015-02-26 21:15:44

标签: r ggplot2

我试图将一个参数传递给scale_y_continuous()而没有运气。我最后一次使用noquote()的尝试如下。我的直觉告诉我这是可行的,但经过多次尝试后我还没想出来。

我想要完成的是:

如果y变量(每组)的最大值<1。 10,将y轴限制固定在c(0,10)。否则修复c(0,20)。另一种选择:否则让y轴自由缩放,即 scale_y_continuous(pretty.breaks,10)或其他一些。

希望我的示例代码足够清晰。实际代码将处理几千个id,因此需要有点健壮。

提前感谢!

data1 <-
structure(list(group = c("AA", "AA", "AA", "AA", "AA", "AA", 
"AA", "AA", "AA", "AA", "AA", "AA", "AA", "AA", "AA", "BB", "BB", 
"BB", "BB", "BB", "BB", "BB", "BB", "BB", "BB", "BB", "BB", "BB", 
"BB", "BB", "CC", "CC", "CC", "CC", "CC", "CC", "CC", "CC", "CC", 
"CC", "CC", "CC", "CC", "CC", "CC"), variable = c(11.453027, 
10.600175, 9.886923, 8.942422, 11.585849, 10.604372, 8.813456, 
9.388578, 9.403585, 10.078807, 10.170484, 10.31884, 10.307227, 
10.720575, 10.974219, 0.7718116, 1.5862548, 0.5691476, 1.3747248, 
1.6671187, 1.5524076, -0.3567432, 0.6318082, 0.681686, 1.9085089, 
0.4098754, 0.2254707, 0.3161615, 0.2456526, 2.66832, 7.776831, 
8.316334, 8.200448, 7.70843, 8.026592, 7.647327, 11.008817, 7.953072, 
8.611409, 9.021719, 8.794007, 8.282669, 9.230021, 9.580956, 6.784829
), xval = c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 
13L, 14L, 15L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 
12L, 13L, 14L, 15L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 
11L, 12L, 13L, 14L, 15L)), class = "data.frame", row.names = c(NA, 
-45L), .Names = c("group", "variable", "xval"))

示例代码:

if(max(data1$variable) < 10) my.scale <- noquote("limits=c(0,10), breaks=seq(0,10, 1)") else my.scale <- noquote("limits=c(0,20), breaks=seq(0,20, 1")

lapply(split(data1,data1$group), function(gg) {

    p1 <-   ggplot(gg,aes(x = xval, y = variable)) + geom_point() +
            geom_line() + theme_bw() +
                scale_y_continuous(my.scale) 

p1
}
)

1 个答案:

答案 0 :(得分:1)

p1 <- ggplot(gg,aes(x = xval, y = variable)) + geom_point() +
        geom_line() + theme_bw()
if(max(data1$variable) < 10){
  p1 <- p1 + scale_y_continuous(limits=c(0,10), breaks=seq(0,10, 1)) 
}

根据需要添加条件......