R: saving ggplot2 plots in a list

前端 未结 2 512
不思量自难忘°
不思量自难忘° 2020-12-10 02:44

I am writing a R code that allows users to select columns from a data and plots histograms for each of them. Hence, I am using a \'for\' loop to generate the required number

2条回答
  •  囚心锁ツ
    2020-12-10 03:45

    You can vastly simplify your code by:

    1. Using facets, rather than manually arranging multiple plots
    2. Melting your data with the function melt in package reshape2
    3. This means you can remove the loop

    Here is a complete rewrite of your code, with no loop in sight.

    data_ <- swiss
    data_ <- na.omit(data_)
    
    u <- c(2, 3, 4, 5, 6)
    plotData <- data_[,u]
    bw <- 5
    plotType <- 'frequency'
    
    library(ggplot2)
    library(reshape2)
    
    mdat <- melt(plotData)
    
    if(plotType=='probability'){
      ph <- ggplot(mdat, aes(value)) +
        geom_histogram(aes(y=..density..), binwidth=bw, colour='black', fill='skyblue') + 
        geom_density() + 
        facet_wrap(~variable, scales="free")
    } 
    
    if(plotType=='frequency'){
      ph <- ggplot(mdat, aes(value)) +
        geom_histogram(aes(y=..count..), binwidth=bw, colour='black', fill='skyblue') + 
        geom_density() + 
        facet_wrap(~variable, scales="free")
    }
    
    print(ph)
    

    The resulting graphics:

    Probability:

    enter image description here

    Frequency

    enter image description here

提交回复
热议问题