Search code examples
rplothistogramstacked

2 stacked histograms with a common x-axis


I want to plot two stacked histograms that share a common x-axis. I want the second histogram to be plotted as the inverse(pointing downward) of the first. I found this post that shows how to plot the stacked histograms (How to plot multiple stacked histograms together in R?). For the sake of simplicity, let's say I just want to plot that same histogram, on the same x-axis but facing in the negative y-axis direction.


Solution

  • You can try something like this:

    ggplot() + 
        stat_bin(data = diamonds,aes(x = depth)) + 
        stat_bin(data = diamonds,aes(x = depth,y = -..count..))
    

    Responding to the additional comment:

    library(dplyr)
    library(tidyr)
    d1 <- diamonds %>% 
            select(depth,table) %>% 
            gather(key = grp,value = val,depth,table)
    
    ggplot() + 
       stat_bin(data = d1,aes(x = val,fill = grp)) + 
       stat_bin(data = diamonds,aes(x = price,y = -..count..))
    

    Visually, that's a bad example because the scales of the variables are all off, but that's the general idea.