Pass variable columns with optional facets in a function via ggplot in R

后端 未结 3 1718
余生分开走
余生分开走 2021-01-03 14:05

I am trying to figure out how to create multiple ggplots with one function, to avoid tedious copying and pasting. I do not want to have to change argument names in the funct

相关标签:
3条回答
  • 2021-01-03 14:26

    Using aes_string will allow you to pass character strings into your ggplot2 function, allowing you to programmatically change it more easily:

    my.plot = function(x, y, data)
    {
    p=ggplot(data, aes_string(x=x, y=y))+geom_bar(stat="identity")
    print(p)
    }
    
    my.plot(x="xVar", y="yVar", data=dataTest)
    

    yvar

    my.plot(x="xVar", y="zVar", data=dataTest)
    

    zvar

    0 讨论(0)
  • 2021-01-03 14:33

    What about using %+% to update the plots instead?

    Example:

    library(ggplot2)
    
    ### sample data ###
    n=25
    dataTest = data.frame(
      xVar=sample(1:3, n, replace=TRUE), 
      yVar = rnorm(n, 5, 2), 
      zVar=rnorm(n, 5, .5) )
    
    p1 <- ggplot(data = dataTest, aes(x = xVar, y = yVar)) + 
      geom_bar(stat = "identity")
    
    aes2 <- aes(x = xVar, y = zVar)
    
    p2 <- p1 %+% aes2
    

    p1:

    enter image description here

    p2:

    enter image description here

    EDIT

    or as @sebastian-c mentioned, aes_string

    plots <- function(x, y, data = dataTest) {
      p1 <- ggplot(data = data, aes_string(x = x, y = y)) + 
        geom_bar(stat = "identity")
    
      p1
    }
    
    plots('xVar','yVar')
    
    plots('xVar','zVar')
    

    EDIT 2: beat me to the punch :o

    0 讨论(0)
  • 2021-01-03 14:37

    Using @sebastian-c's answer and other sources, I have a function that I think will work and I wanted to share it. I think I see @Henrik's solution, but it seems like more typing, as I have 4 groups, 4 'x' categories, and a third category related to time (year, quarters, months).

    library(ggplot2)
    
    ### sample data ###
    n=25
    dataTest = data.frame(
      xVar=sample(1:3, n, replace=TRUE), 
      yVar = rnorm(n, 5, 2), 
      zVar=rnorm(n, 5, .5),
      brand=letters[1:5])
    
    ### function
    my.plot = function(x, y, data, group=NULL)
    {
      p=ggplot(data, aes_string(x=x, y=y, fill=group))+
        geom_bar(stat="identity")
      # make a facet if group is not null
      if(length(group)>0) {
        facets = facet_wrap(formula(paste("~", group)))
        p = p + facets
      }
      return(p)
    } 
    
    0 讨论(0)
提交回复
热议问题