0

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.

Community
  • 1
  • 1
struggleBus
  • 365
  • 2
  • 5
  • 20

2 Answers2

3

You could count up cases and then multiply the count by -1 for one category. Example with data.table / ggplot

library(data.table)
library(ggplot2)

# fake data
set.seed(123)
dat <- data.table(value = factor(sample(1:5, 200, replace=T)),
                  category = sample(c('a', 'b'), 200, replace=T))

# count by val/category; cat b as negative
plot_dat <-
   dat[, .(N = .N * ifelse(category=='a', 1, -1)), 
       by=.(value, category)]

# plot
ggplot(plot_dat, aes(x=value, y=N, fill=category)) +
  geom_bar(stat='identity', position='identity') +
  theme_classic()

enter image description here

arvi1000
  • 9,393
  • 2
  • 42
  • 52
  • and I can subdivide a and b into other categories that would also plot as stacked? Also, my Rstudio is not recognizing the '.' function. I have never used that before, what does it do? – struggleBus Oct 12 '15 at 15:49
1

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.

joran
  • 169,992
  • 32
  • 429
  • 468
  • thanks @joran. This is a good start. but how do I make those histograms stacked? for example, if I wanted to plot depth and table on the top and clarity and price on the bottom? – struggleBus Oct 12 '15 at 16:23
  • nevermind, I figured it out using your same aes() commands but in the geom_histogram function with position='stacked'! – struggleBus Oct 12 '15 at 16:32