Reputation: 1814
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)
Upvotes: 1
Views: 1157
Reputation: 11728
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)
}
Upvotes: 5