【问题标题】:calculate a value from several rows based on condition on some columns in R根据 R 中某些列的条件从几行计算一个值
【发布时间】:2021-06-19 17:43:45
【问题描述】:

我有一个这样的数据集:

year      city       type   sex  number
2008      London      A      F    100
2008      London      B      F    110
2008      London      A      M    101
2008      London      B      M    111
2009      London      A      F    200
2009      London      B      F    210
2009      London      A      M    201
2009      London      B      M    211
2008      NY          A      F    100
2008      NY          B      F    110
2008      NY          A      M    101
2008      NY          B      M    111
2009      NY          A      F    200
2009      NY          B      F    210
2009      NY          A      M    201
2009      NY          B      M    211

我想以这样一种方式绘制它们,每年我都有 F 和 M 的总和作为堆栈图的两个部分,并显示每个项目的百分比。

如何在 R 中做到这一点?

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    我们可以通过tidyverse 方法做到这一点

    1. 按“年份”、“性别”列分组
    2. summarise 中获取“号码”的sum
    3. 通过将汇总除以列的sum 来创建列“perc”
    4. x 指定为“年份”,将y 指定为“数字”之和,将fill 指定为“性别”,并将ggplotaeslabel 的“perc”指定为ggplot
    5. 使用geom_col 返回条形图
    6. geom_text添加百分比标签
    library(dplyr)
    library(ggplot2)
    df1 %>% 
        group_by(year, sex) %>% 
        summarise(number = sum(number), .groups = 'drop') %>% 
        mutate(perc =  number/sum(number), year = factor(year)) %>% 
        ggplot(aes(x = year, y = number, fill = sex, 
                label = scales::percent(perc))) + 
          geom_col(position = 'dodge') + 
          geom_text(position = position_dodge(width = .9),  
                  vjust = -0.5,   
                   size = 3) +      
          theme_bw()
    

    -输出

    数据

    df1 <- structure(list(year = c(2008L, 2008L, 2008L, 2008L, 2009L, 2009L, 
    2009L, 2009L, 2008L, 2008L, 2008L, 2008L, 2009L, 2009L, 2009L, 
    2009L), city = c("London", "London", "London", "London", "London", 
    "London", "London", "London", "NY", "NY", "NY", "NY", "NY", "NY", 
    "NY", "NY"), type = c("A", "B", "A", "B", "A", "B", "A", "B", 
    "A", "B", "A", "B", "A", "B", "A", "B"), sex = c("F", "F", "M", 
    "M", "F", "F", "M", "M", "F", "F", "M", "M", "F", "F", "M", "M"
    ), number = c(100L, 110L, 101L, 111L, 200L, 210L, 201L, 211L, 
    100L, 110L, 101L, 111L, 200L, 210L, 201L, 211L)), 
    class = "data.frame", row.names = c(NA, 
    -16L))
    

    【讨论】:

    • 这是有效的。如何将 precents 标签移动到栏中并旋转 90 度?
    • @mans 在 geom_text 中,我指定了 position_dodgev_just。我认为您可以更改这些值
    • 我和他们一起玩过,但直到现在都没有成功。做更多的研究和反复试验,看看我怎么能做到这一点。
    • @mans 当你说你想搬进酒吧时。你到底想搬到哪里。是在中间还是顶部还是底部
    • 并不重要,但可能是中间
    猜你喜欢
    • 1970-01-01
    • 2021-02-16
    • 2019-08-03
    • 2021-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多