arrange multiple graphs using a for loop in ggplot2

前端 未结 4 857
有刺的猬
有刺的猬 2021-02-04 19:37

I want to produce a pdf which shows multiple graphs, one for each NetworkTrackingPixelId. I have a data frame similar to this:

> head(data)
  Net         


        
4条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-04 20:15

    Since I don't have your dataset, I will use the mtcars dataset to illustrate how to do this using dplyr and data.table. Both packages are the finest examples of the split-apply-combine paradigm in rstats. Let me explain:

    Step 1 Split data by gear

    • dplyr uses the function group_by
    • data.table uses argument by

    Step 2: Apply a function

    • dplyr uses do to which you can pass a function that uses the pieces x.
    • data.table interprets the variables to the function in context of each piece.

    Step 3: Combine

    There is no combine step here, since we are saving the charts created to file.

    library(dplyr)
    mtcars %.%
      group_by(gear) %.%
      do(function(x){ggsave(
        filename = sprintf("gear_%s.pdf", unique(x$gear)), qplot(wt, mpg, data = x)
      )})
    
    library(data.table)
    mtcars_dt = data.table(mtcars)
    mtcars_dt[,ggsave(
      filename = sprintf("gear_%s.pdf", unique(gear)), qplot(wt, mpg)),
      by = gear
    ]
    

    UPDATE: To save all files into one pdf, here is a quick solution.

    plots = mtcars %.%
      group_by(gear) %.%
      do(function(x) {
        qplot(wt, mpg, data = x)
      })
    
    pdf('all.pdf')
    invisible(lapply(plots, print))
    dev.off()
    

提交回复
热议问题