【问题标题】:2 stacked histograms with a common x-axis2 个具有共同 x 轴的堆叠直方图
【发布时间】:2015-10-12 14:48:24
【问题描述】:

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

【问题讨论】:

    标签: r plot histogram stacked


    【解决方案1】:

    您可以对案例进行计数,然后将计数乘以 -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()
    

    【讨论】:

    • 我可以将 a 和 b 细分为其他类别,这些类别也可以堆叠显示?此外,我的 Rstudio 无法识别“。”。功能。没用过,有什么用?
    【解决方案2】:

    你可以试试这样的:

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

    从视觉上看,这是一个不好的例子,因为变量的尺度都没有,但这是一般的想法。

    【讨论】:

    • 感谢@joran。这是一个好的开始。但是如何使这些直方图堆叠?例如,如果我想在顶部绘制深度和表格,在底部绘制清晰度和价格?
    • 没关系,我使用您相同的 aes() 命令但在 geom_histogram 函数中使用 position='stacked' 解决了这个问题!
    猜你喜欢
    • 2020-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-09
    • 1970-01-01
    相关资源
    最近更新 更多