0

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!

jpsmith
  • 11,023
  • 5
  • 15
  • 36
helpneeder
  • 31
  • 5

1 Answers1

1

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

akrun
  • 874,273
  • 37
  • 540
  • 662
TarJae
  • 72,363
  • 6
  • 19
  • 66
  • Thank you! Would you be able to add a line of code that explains how to manually select the colors for each histogram? – helpneeder Apr 16 '23 at 21:24