Histogram with two variables in ggplot

16,090

You need to convert DF to long format using something like tidyr::gather...

library(tidyr)
library(ggplot2)

DF %>% 
  gather(key=Type, value=Value) %>% 
  ggplot(aes(x=Value,fill=Type)) + 
  geom_histogram(position="dodge")

enter image description here

Share:
16,090

Related videos on Youtube

KaC
Author by

KaC

Updated on June 04, 2022

Comments

  • KaC
    KaC almost 2 years

    I have a dataframe with two variables:

    DF <- data.frame(Now = as.numeric(c(1, 6, 4, 4, 5, 6)), Before = as.numeric(c(1, 6, 3, 5, 10, 10)))
    

    I can easily plot both variables separately:

    library(ggplot2)
    ggplot(DF, aes(Now))+
      geom_histogram()
    ggplot(DF, aes(Before))+
      geom_histogram()
    

    But I would like to plot both variables together, so that the change between Before and Now is easy to see. One way to do this is described in an answer here: Plot two variables in the same histogram with ggplot. But I would much rather have one plot with differently colored bars side-by-side. How can this be done? (Side note: if it's easier to do with geom_bar than geom_histogram, that works for me too.)

    • Punintended
      Punintended almost 6 years
      Andrew Gustar has already answered this, but it's a duplicate of this question
    • KaC
      KaC almost 6 years
      Thanks. Search didn't return that question.
    • Punintended
      Punintended almost 6 years
      Only reason I found it easily is 'cause I checked my answer history ;)