Search code examples
rggplot2histogram

Plotting 2 histogram on top and bottom part of a single plot


I want to draw two histogram on same plot window but placed vertically. One such example can be found at https://blogs.sas.com/content/graphicallyspeaking/files/2013/11/MirrorHistogramVert.png

Below is my code

library(ggplot2)
set.seed(1)
dat = rbind(data.frame('val' = rnorm(100), 'met' = 'Metric1'), data.frame('val' = rt(100, 2), 'met' = 'Metric12'))

ggplot(dat, aes(x = val, y = met, color = met)) + geom_histogram()

However I am getting below error

Error in `geom_histogram()`:
! Problem while computing stat.
ℹ Error occurred in the 1st layer.
Caused by error in `setup_params()`:
! `stat_bin()` must only have an x or y aesthetic.
Run `rlang::last_trace()` to see where the error occurred.

I also want to add probability curve for Normal distribution for both histogram.

Any suggestion what could be the right approach will be very helpful


Solution

  • You could do two separate layers for the two groups, using y = -after_stat(count) in the second layer (the default for geom_histogram is y = after_stat(count).

    Ensure the breaks for both layers are the same so that the bins line up.

    ggplot(dat, aes(x = val, fill = met)) + 
      geom_histogram(data    = dat[dat$met == 'Metric1',], 
                     breaks  = seq(-40, 10, 0.5),
                     colour  = "black",
                     alpha   = 0.3) +
      geom_histogram(data    = dat[dat$met == 'Metric12', ],
                     breaks  = seq(-40, 10, 0.5),
                     mapping = aes(y = -after_stat(count)),
                     colour  = "black",
                     alpha   = 0.3) +
      scale_fill_manual(values = c('blue3', 'red3')) +
      coord_cartesian(xlim = c(-10, 10)) +
      labs(y = 'count') +
      theme_bw(20) +
      theme(panel.border = element_blank())
    

    enter image description here