通过循环在ggplot2中设置图层

时间:2013-08-26 12:52:43

标签: r ggplot2

我希望

data <- data.frame(col1 = c(1, 2, 2, 3, 3, 4),
                   col2 = c(1, 2, 2, 1, 2, 1),
                   z = rnorm(6))
p1<-ggplot(data, aes(x=col1))

for(idx in unique(data$col2)){
    p1<-p1 + geom_bar(subset = .(col2 == idx), aes(y = ..count..),fill = "blue", alpha = 0.2)
}
p1

具有与

相同的输出
p1<-ggplot(data, aes(x=col1))
p1<-p1 + geom_bar(subset = .(col2 == 1), aes(y = ..count..),fill = "blue", alpha = 0.2)
p1<-p1 + geom_bar(subset = .(col2 == 2), aes(y = ..count..),fill = "blue", alpha = 0.2)
p1

但事实并非如此。那么我怎样才能在for循环中产生与第二个例子中相同的输出。

1 个答案:

答案 0 :(得分:2)

如果您自己进行子集化,这个问题很简单:

library(ggplot2)
data <- data.frame(
  col1 = c(1, 2, 2, 3, 3, 4),
  col2 = c(1, 2, 2, 1, 2, 1),
  z = rnorm(6))
ids <- unique(data$col2)

p1 <- ggplot(data, aes(col1, y = ..count..))

for(id in ids){
  df <- data[data$col2 == id, ]
  p1 <- p1 + geom_bar(data = df, fill = "blue", alpha = 0.2)
}
p1