代码之家  ›  专栏  ›  技术社区  ›  ChinaskyM

根据第三个变量显示百分比,带有两个分类变量facet\u wrap的ggplot 2的条形图

  •  1
  • ChinaskyM  · 技术社区  · 7 年前

    我想在ggplot2中绘制一个分类变量,根据第二个分类变量分组,并使用facet\u wrap将它们划分到不同的图中。 我会显示每个的百分比。这里是一个可复制的示例

    test <- data.frame(
      test1 = sample(letters[1:2], 100, replace = TRUE), 
      test2 = sample(letters[3:5], 100, replace = TRUE),
      test3 = sample(letters[9:11],100, replace = TRUE )
    )
    
    
    ggplot(test, aes(x=factor(test1))) +
      geom_bar(aes(fill=factor(test2), y=..prop.., group=factor(test2)), position="dodge") +
      facet_wrap(~factor(test3))+
      scale_y_continuous("Percentage (%)", limits = c(0, 1), breaks = seq(0, 1, by=0.1), labels = percent)+
      scale_x_discrete("")+
      theme(plot.title = element_text(hjust = 0.5), panel.grid.major.x = element_blank())
    

    这给了我一个条形图,其中每个test3中test2与test1的百分比。 我想在顶部显示每个条的百分比。此外,我想将右侧图例的名称从test2中的因子(test2)更改为。

    enter image description here

    1 回复  |  直到 7 年前
        1
  •  4
  •   Luke C    7 年前

    自己进行数据汇总可能是最容易的,这样就可以创建一个包含所需百分比标签的列。(注意,实际上,我不确定您希望百分比显示什么-在方面一,b组中,有一列接近90%,两列大于或等于50%——这是有意的吗?)

    库和示例数据框:

    library(ggplot2)
    library(dplyr)
    
    test <- data.frame(
      test1 = sample(letters[1:2], 100, replace = TRUE), 
      test2 = sample(letters[3:5], 100, replace = TRUE),
      test3 = sample(letters[9:11],100, replace = TRUE )
    )
    

    首先,按所有列分组(注意顺序),然后汇总以获得 length 属于 test2 . Mutate 获取列高度和标签的值- 这里我乘以100并四舍五入。

    test.grouped <- test %>%
      group_by(test1, test3, test2) %>%
      summarize(t2.len = length(test2)) %>%
      mutate(t2.prop = round(t2.len / sum(t2.len) * 100, 1))
    
    > test.grouped
    # A tibble: 18 x 5
    # Groups:   test1, test3 [6]
        test1  test3  test2 t2.len t2.prop
       <fctr> <fctr> <fctr>  <int>   <dbl>
     1      a      i      c      4    30.8
     2      a      i      d      5    38.5
     3      a      i      e      4    30.8
     4      a      j      c      3    20.0
     5      a      j      d      8    53.3
    ...
    

    使用汇总数据构建绘图,使用 geom_text 要使用“比例”列作为标签,请执行以下操作:

    ggplot(test.grouped, aes(x = test1, 
                             y = t2.prop, 
                             fill = test2, 
                             group = test2)) +  
      geom_bar(stat = "identity", position = position_dodge(width = 0.9)) +
      geom_text(aes(label = paste(t2.prop, "%", sep = ""), 
                    group = test2), 
                position = position_dodge(width = 0.9),
                vjust = -0.8)+
      facet_wrap(~ test3) + 
      scale_y_continuous("Percentage (%)") +
      scale_x_discrete("") + 
      theme(plot.title = element_text(hjust = 0.5), panel.grid.major.x = element_blank())
    

    enter image description here