Histogram, compare distributionof 2 variables

How do I create a histogram that shows the distribution of 2 variables with the same x-axis variable in the same graph?

Thank you

The simplest way is to use ggplot2. The easiest in that case is to store both distributions in a single data frame (or tibble).

library(tidyverse) #includes ggplot2 and tibble-manipulating functions

# example data
a <- rnorm(100, 7)
b <- rnorm(200, 9)

# gather the data in a tibble
dta <- tibble(group = rep(c("a", "b"), c(100, 200)),
              values = c(a, b))

ggplot(dta) +
  geom_histogram(aes(x = values, fill = group))

The trick to overlaying them is to use transparency (alpha), and to specify the position (the default is 'stack', which is probably not what you want).

ggplot(dta) +
  geom_histogram(aes(x = values, fill = group),
                 alpha = .5, position = "identity", bins = 30) +
  theme_classic() +
  scale_fill_brewer(type="qual", palette="Set1")

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.