0

我本来希望

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 循环中产生与第二个示例相同的输出。

4

1 回答 1

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
于 2013-08-27T16:12:08.777 回答