0

I have this data set:

x <- sample(80)
matrix <- matrix(x, ncol=5, nrow=16)
matrix <- cbind(matrix, c(rep("group1",4), rep("group2",4), rep("group3",4), rep("group4",4)))
colnames(matrix) <- c(letters[1:5], "groups")
df <- as.data.frame(matrix)

I would like to be able to plot five boxplots, one for each column from a to e, using a for loop. I have tried this, but I cannot figure out how to make it work:

for(i in df[,1:5]) {
  p <- ggplot(df, aes(x=groups, y=as.numeric(as.character(i))))
  p +  geom_boxplot()
}
0

1 Answer 1

3

I'm guessing here:

library(reshape)
ggplot(melt(df, id.vars="groups")) + geom_boxplot(aes(x=groups, y=as.numeric(value))) + facet_wrap(~variable)

gives

enter image description here

and

library(reshape)
ggplot(melt(df, id.vars="groups")) + geom_boxplot(aes(x=groups, y=as.numeric(value)), color=variable)

gives

enter image description here

Is any of that close to what you want?

Sign up to request clarification or add additional context in comments.

5 Comments

For example 1: is there a way to keep the group names in each plot?
@Sergio.pv Yes, in this particular case, use facet_wrap(~variable, scales="free_x")
@Sergio.pv You might want to take a look on the cookbook for more information.
is there a way to add a general title to the facet?. I couldn't find an answer in the coockbook.
@Sergio.pv See here + labs(title="test")

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.