Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating Multiple Plots in ggplot by Factor

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.

like image 332
riders994 Avatar asked Aug 03 '15 23:08

riders994


People also ask

How do I plot multiple Ggplots together?

To arrange multiple ggplot2 graphs on the same page, the standard R functions - par() and layout() - cannot be used. The basic solution is to use the gridExtra R package, which comes with the following functions: grid. arrange() and arrangeGrob() to arrange multiple ggplots on one page.

What is a Grob in Ggplot?

First off a grob is just short for “grid graphical object” from the low-level graphics package grid; Think of it as a set of instructions for create a graphical object (i.e. a plot). The graphics library underneath all of ggplot2's graphical elements are really composed of grob's because ggplot2 uses grid underneath.


1 Answers

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() )
}
like image 145
Rorschach Avatar answered Oct 17 '22 09:10

Rorschach