2 个具有共同 x 轴的堆叠直方图

2 stacked histograms with a common x-axis

我想绘制共享公共 x 轴的两个堆叠直方图。我希望将第二个直方图绘制为第一个的倒数(指向下方)。我发现这个 post 显示了如何绘制堆叠直方图 (How to plot multiple stacked histograms together in R?)。为了简单起见,假设我只想在相同的 x 轴上绘制相同的直方图,但面向负 y 轴方向。

您可以对案例进行计数,然后将一个类别的计数乘以 -1。 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()

您可以尝试这样的操作:

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

回复附加评论:

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

从视觉上看,这是一个糟糕的例子,因为变量的尺度都偏离了,但这是一般的想法。