0

I would expected that

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

have the same output like

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

but it istn't. So how could I produce in the for loop the same output like in the second example.

11
  • What kind of plot are you looking for? Your working example does not make sense to me. Commented Aug 26, 2013 at 13:11
  • 1
    I'm thinking he can make the plot without explicitly subsetting the data Commented Aug 26, 2013 at 13:16
  • Thierry iam speaking about a principle @Pete I know for example if I would melt the data frame by col2. But I am interrested doing this by for loop or any other loop to have the result if I would write the sequenz explicte like in the first example. Commented Aug 26, 2013 at 13:28
  • Subset the data yourself inside the loop - your loop doesn't work because idx == 2 at the end and that's what both layers will see. Commented Aug 26, 2013 at 14:12
  • @hadley, I know but I dont understand the this behavior, because for me the code in the loop looks like I would add in each step a knew layer. Commented Aug 26, 2013 at 14:55

1 Answer 1

2

This problem is simple if you do the subsetting yourself:

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
Sign up to request clarification or add additional context in comments.

1 Comment

Many thx. This was exactly what I tried before but it doesnt worked till now. p1 <- ggplot(data, aes(x=col1)) df<-split(data, data$col2) for(i in df){ p1 <- p1 + geom_bar(data = i, aes(y = ..count..), fill = "blue", alpha = 0.2) } p1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.