【问题标题】:ggplot2. How to make geom_bar stacked chart y-range 0-100%?ggplot2。如何使 geom_bar 堆积图 y 范围 0-100%?
【发布时间】:2020-07-16 05:48:10
【问题描述】:

使用 stat = "identity" 的 geom_bar 时,y 轴最大值是所有值的总和。在此示例中,我希望 y 轴最大值为 100 而不是 300,并且堆积条形图显示每个复制品的条形比例。有谁知道我该怎么做?

dat = data.frame(sample = c(rep(1, 12),
                            rep(2, 9),
                            rep(3, 6)),
                 category = c(rep(c("A", "B", "C"), each = 4),
                              rep(c("A", "B", "C"), each = 3),
                              rep(c("A", "B", "C"), each = 2)),
                 replicate = c(rep(c("a", "b", "c", "d"), 3),
                               rep(c("a", "b", "c"), 3),
                               rep(c("a", "b"), 3)),
                 value = c(rep(25, 12),
                           rep(c(25, 25, 50), 3),
                           rep(50, 6))
                 )

ggplot(dat, 
       aes(x = sample, y = value)) +
  geom_bar(aes(fill = replicate),
           stat = "identity")

【问题讨论】:

    标签: r ggplot2 geom-bar stacked-chart


    【解决方案1】:

    一种方法是在绘图之前预先计算值。

    library(dplyr)
    library(ggplot2)
    
    dat %>%
       group_by(sample) %>%
       mutate(value = value/sum(value) * 100) %>%
       ggplot() + aes(x = sample, y = value, fill = replicate) +
       geom_col()  +
       ylab('value  %')
    

    【讨论】:

    • 也许 y-lab 应该是“样本百分比”或“值 (%)”
    • 是的..谢谢。那更准确。更新了答案。
    猜你喜欢
    • 2016-03-18
    • 1970-01-01
    • 1970-01-01
    • 2015-03-18
    • 1970-01-01
    • 2019-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多