Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a ribbon when faceting in ggplot2

Tags:

r

ggplot2

I have a facet grid ggplot2 graph in R, which I am trying to overlay a horizontal line and a ribbon for each facet. I have made separate data frames for the horizontal line and ribbon values, respectively. However, I am running into problems with an 'object not found error' when adding the ribbon.

Below is some reproducible code.

# create DF
df1 = data.frame( x = rep(letters[1:4], 4),
              y = rnorm(16, 0 , 1),
              group = rep(1:4, each=4))

# horizonal line DF
hLines = data.frame(group = unique(df1$group) , 
                y = aggregate(y ~ group, data=df1 , FUN=mean)[2] )

# CIs DF
hCIs = data.frame(group = unique(df1$group), 
              low = hLines$y -  (2 * aggregate(y ~ group, data=df1 , FUN=sd)[2] ),
              high = hLines$y + (2 * aggregate(y ~ group, data=df1 , FUN=sd)[2] ) )

ggplot(df1 , aes(x = x , y = y)) +
  facet_grid(~group) +
  geom_point(size=3) +
  geom_hline(data=hLines, aes(yintercept = y))+
  geom_ribbon(data=hCIs, aes(x=x, ymin=low, ymax=high))+
  theme_bw()

When the geom_ribbon command is not included, it works. But when I try to add the ribbon, I get:

Error in eval(expr, envir, enclos) : object 'low' not found

Thanks a lot for your help.

EDIT: I made a mistake in the column names of hCIs. However, when specifying:

colnames(hCIs) = c("group", "low", "high")

...I still receive an error:

Error: Aesthetics must be either length 1 or the same as the data (4): x, ymin, ymax, y

like image 718
user3237820 Avatar asked Jun 24 '16 13:06

user3237820


1 Answers

Your geom_ribbon has no info on what x is as you are specifying a new data source: hCIs without the x.

Buit if you merge the 2 dataframes to get an x value for each hCIs datapoint then this works:

ggplot(df1 , aes(x = x , y = y)) +
    facet_grid(~group) +
    geom_point(size=3) +
    geom_hline(data=hLines, aes(yintercept = y))+
    geom_ribbon(data=merge(hCIs, df1), aes(ymin=low, ymax=high, group = group), alpha = 0.2)+
    theme_bw()

enter image description here

like image 72
niczky12 Avatar answered Oct 23 '22 13:10

niczky12