Search code examples
rggplot2facet-gridcustom-functiongeom-hline

geom_hline or geom_vline does not seem to accept vector for reference line, if called inside a function and facet_grid() is used


I have been facing issue with geom_hline or geom_vline if I call it under custom function and it takes the value from a vector. It seems to work fine until I add facet_grid() within that function body.e.g Without Function

c<- data.frame(A = c("carr","bike","truck","carr","truck","bike","bike","carr","truck","carr","truck","truck","carr","truck","truck"),
                B = c(10,20,30,23,45,56,78,44,10,20,30,10,20,30,67),
                D = c(1,2,3,1,2,3,2,3,2,3,2,2,3,2,1))
a = c(1:4)*4
ggplot(c, aes(A,B, color = D))+
  geom_point()+
  facet_grid( .~D)+
  geom_hline(yintercept = a,linetype = "dotted",size =0.3)

`

I get this: enter image description here

But With Function

    tk_fun <- function(dat,x1,y1,clr){   # I need to have this a declared and defined with in function.  
 a = c(1:4)*4.5  p <- ggplot(dat, aes_string(colnames(dat)[1],colnames(dat)[2], color = colnames(dat)[3]))+
    geom_point()+    facet_grid( .~dat[,3])+
    geom_hline(yintercept = a,linetype = "dotted",size =0.3)  return(p) } tk_fun(c,"A","B","D")

With function I am getting this error:

Error in $<-.data.frame(*tmp*, "PANEL", value = c(1L, 2L, 3L, 1L, : replacement has 15 rows, data has 4 I hope someone can help me in figuring out, how to do it through function, without an error. Thanks


Solution

  • The problem is with your definition of the facets. You need to create an appropriate formula call with the correct variable name, not use the data directly. Using paste and as.formula can help here.

    tk_fun <- function(dat,x1,y1,clr){   # I need to have this a declared and defined with in function.  
      a = c(1:4)*4.5  
      p <- ggplot(dat, aes_string(colnames(dat)[1],colnames(dat)[2], color = colnames(dat)[3]))+
        geom_point() +
        facet_grid(as.formula(paste('. ~', names(dat)[3]))) +
        geom_hline(yintercept = a, linetype = "dotted", size =0.3)  
      return(p) 
    }