20

I have a data set that I want to generate multiple plots for based on one of the columns. That is, I want to be able to use ggplot to make a separate plot for each variety of that factor.

Here's some quick sample data:

Variety = as.factor(c("a","b","a","b","a","b","a","b","a","b")
Var1 = runif(10)
Var2 = runif(10)
mydata = as.data.frame(cbind(Variety,Var1,Var2))

I'd like to generate two separate plots of Var1 over Var2, one for Variety A, a second for Variety B, preferably in a single command, but if there's a way to do it without splitting the table, that would be ok as well.

Rorschach
  • 31,301
  • 5
  • 78
  • 129
riders994
  • 1,246
  • 5
  • 13
  • 33

1 Answers1

37

You can use facet_grid or facet_wrap to split up graphs by factors.

ggplot(mydata, aes(Var1, Var2)) + geom_point() + facet_grid(~ Variety)

or, on separate plots, just use a simple loop

for (var in unique(mydata$Variety)) {
    dev.new()
    print( ggplot(mydata[mydata$Variety==var,], aes(Var1, Var2)) + geom_point() )
}
Rorschach
  • 31,301
  • 5
  • 78
  • 129
  • Ah, thank you. I'm going to try it out, but that should definitely work. – riders994 Aug 04 '15 at 04:22
  • 2
    @pickle rick in your for solution, is there a way to label each individual plot so you know which is which? (in other words, add a title to each) – Emily Feb 11 '20 at 04:33
  • 3
    @Emily when you use the second option (with the loop) you can simply add "+ ggtitle(var)". In this case the plots will get the name of the variety as title – Tingolfin Jun 27 '20 at 13:41