Search code examples
rggplot2histogram

Is there a way to overlay three histograms (with three different colors) in R?


I was just wondering if anyone knew how to overlay three different histograms over each other within one plot in R. Say you have three variables:

x <- c(1.5,2.1,3.6,4.2,5.6) 
y <- c(2.5,2.1,1.6,3.2,4.6)
z <- c(0.5,1.5,2.6,2.2,3.6)

If you run a histogram for each of those variables and then you want to put those three histograms on top of each other (overlay all three histograms) in the same plot with each histogram being in a different color, how would you do that?

Thank you!


Solution

  • Here is how we could do it:

    library(dplyr)
    library(ggplot2)
    
     df1 <- data.frame(values = c(rnorm(1000, 2, 3),
                                  rnorm(1000, 3, 2),
                                  runif(1000, 4, 11)),
                                  group = c(rep("x", 1000),
                                            rep("y", 1000),
                                            rep("z", 1000)))
      ggplot(df1, aes(x = values, y=100*(..count..)/sum(..count..),
             fill = group)) +      
        geom_histogram(position = "identity", alpha = 0.5, bins = 70)+
        ylab("percent")+
        theme_minimal()
    

    enter image description here