arrange multiple graphs using a for loop in ggplot2

前端 未结 4 853
有刺的猬
有刺的猬 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 19:53

    Unless I'm missing something, generating plots by a subsetting variable is very simple. You can use split(...) to split the original data into a list of data frames by NetworkTrackingPixelId, and then pass those to ggplot using lapply(...). Most of the code below is just to crate a sample dataset.

    # create sample data
    set.seed(1)
    names <- c("Rubicon","Google","OpenX","AppNexus","Pubmatic")
    dates <- as.Date("2014-02-16")+1:10
    df <- data.frame(NetworkTrackingPixelId=rep(1:5,each=10),
                     Name=sample(names,50,replace=T),
                     Date=dates,
                     Impressions=sample(1000:10000,50))
    # end create sample data
    
    pdf("plots.pdf")
    lapply(split(df,df$NetworkTrackingPixelId),
           function(gg) ggplot(gg,aes(x = Date, y = Impressions)) + 
              geom_point() + geom_line()+
              ggtitle(paste("NetworkTrackingPixelId:",gg$NetworkTrackingPixelId)))
    dev.off()
    

    This generates a pdf containing 5 plots, one for each NetworkTrackingPixelId.

提交回复
热议问题