Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Highlight data individually with facet_grid in R

Tags:

r

ggplot2

facet

I am using facet_grid in R to plot RT data for 5 different groups. I would like to highlight the data between 5 and 95% for each group.

With the code below, I am using the percentile of the entire data frame, not the one for each group. Any idea of how I can still use facet_grid and have the unique percentile of each group highlighted in the plot.

rect <- data.frame (xmin=quantile(ss$RT, c(0.05)), 
                    xmax=quantile(ss$RT, c(0.95)), 
                    ymin=-Inf, ymax=Inf)


qplot(prevRT, RT, group=ss, color = prim, 
      geom = c("smooth"), 
      method="lm", data =ss) + 
   facet_grid(~ Groupe) + 
   geom_rect(data=rect, 
             aes(xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax), 
             color="grey20", alpha=0.5, inherit.aes = FALSE)
like image 677
Alba Avatar asked Sep 18 '12 22:09

Alba


People also ask

What is the difference between Facet_wrap and Facet_grid?

The facet_grid() function will produce a grid of plots for each combination of variables that you specify, even if some plots are empty. The facet_wrap() function will only produce plots for the combinations of variables that have values, which means it won't produce any empty plots.

What is the function of Facet_grid () in Ggplot ()?

facet_grid() forms a matrix of panels defined by row and column faceting variables. It is most useful when you have two discrete variables, and all combinations of the variables exist in the data. If you have only one variable with many levels, try facet_wrap() .

What is a faceted plot in R?

The facet approach partitions a plot into a matrix of panels. Each panel shows a different subset of the data. This R tutorial describes how to split a graph using ggplot2 package.


1 Answers

Thanks to DWin's suggestion, I used ave to find xmin and xmax for each group individually and incorporated that directly into the command for the plot.

There is probably a more elegant way to do that (and suggestions are welcome), but it works.

qplot(prevRT, RT, group=ss, color = prim, 
 geom = c("smooth"), 
 method="lm", data =ss) + 
 facet_grid(~ Groupe) + 
 geom_rect(data=ss, 
      aes(xmin=ave(ss$RT, ss$Groupe, FUN = function(x)quantile(x,c(0.05))),      
      xmax=ave(ss$RT, ss$Groupe, FUN = function(x)quantile(x,c(0.95))),
      ymin=-Inf,ymax=Inf), color="green", alpha=1/280, inherit.aes = FALSE)

enter image description here

like image 105
Alba Avatar answered Nov 04 '22 06:11

Alba