1

I want to loop ggplot and obtain a graph for each variable code is below. I get an error in aes

df <- data.frame(ID = c("a", "b"), A = rnorm(2), B = runif(2), C = rlnorm(2))
for(i in df[,2:ncol(df)]){
 plt<-ggplot(data=df, aes(x=df$ID, y = df[,2:ncol(df)]$i))+
    geom_bar()
  print(plt)
}

What is the problem?

I know I could use facet_grid.

ggplot(df_melt, aes(x=ID,y=value)) + geom_bar(stat="identity") + facet_grid(~variable)

1 Answer 1

5
df <- data.frame(ID = c("a", "b"), A = rnorm(2), B = runif(2), C = rlnorm(2))

for (colname in names(df)[-1]) {
  plt <- ggplot(data = df, aes_string("ID", y = colname)) +
    geom_bar(stat = "identity")
  print(plt)
}
Sign up to request clarification or add additional context in comments.

1 Comment

Note that you can now replace geom_bar(stat = "identity") by geom_col().

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.