简体   繁体   English

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

[英]2 stacked histograms with a common x-axis

I want to plot two stacked histograms that share a common x-axis. 我想绘制两个共享x轴的堆叠直方图。 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? ). 我发现这篇文章显示了如何绘制堆叠的直方图( 如何在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. 为了简单起见,假设我只想在相同的x轴上绘制相同的直方图,但面向负y轴方向。

You could count up cases and then multiply the count by -1 for one category. 您可以对个案进行计数,然后将一个类别的计数乘以-1。 Example with data.table / ggplot 示例与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. 从视觉上看,这是一个糟糕的例子,因为变量的标度全都没有了,但这是一般的想法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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