简体   繁体   中英

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.

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()

在此处输入图片说明

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM