【问题标题】:ggplot2: add labels to percentage plot (not position=fill, but just fill)ggplot2:将标签添加到百分比图(不是位置=填充,而只是填充)
【发布时间】:2020-04-19 17:32:45
【问题描述】:

我想为百分比条形图添加百分比标签

我通过position="fill" (Add percentage labels to a stacked barplot) 和这里 (How to draw stacked bars in ggplot2 that show percentages based on group?) 找到了解决方案,但是,我想为每个组保留相对频率。

这是一个示例图:

# library
library(ggplot2)

# data  
df <- data.frame(group=c("A","A","A","A","B","B","B","C","C"),
                   anon=c("yes","no","no","no","yes","yes","no","no","no"))

# percentage barplot
  ggplot(df, aes(group),fill=anon) + 
    geom_bar(aes(y = (..count..)/sum(..count..),fill=anon)) + 
    scale_y_continuous(labels=scales::percent) +
    ylab("relative frequencies")

reprex package (v0.3.0) 于 2020 年 4 月 19 日创建

现在我想为每个条形的每个红色和绿色部分添加百分比标签,以便获得“相对相对”(例如,A 组的“是”为 25%)值。 如何才能做到这一点?我是否必须为此更改我的 df 或者这在 ggplot 函数中是否有可能

【问题讨论】:

    标签: r ggplot2 percentage


    【解决方案1】:

    一种可能的解决方案是计算ggplot2 之外的比例,这里我使用dplyr 来计算这些不同的比例:

    library(dplyr)
    
    df_calculated <- df %>% count(group, anon) %>%
      mutate(Percent_col = n / sum(n)) %>%
      group_by(group) %>%
      mutate(Percent = n/sum(n))
    
    # A tibble: 5 x 5
    # Groups:   group [3]
      group anon      n Percent_col Percent
      <fct> <fct> <int>       <dbl>   <dbl>
    1 A     no        3       0.333   0.75 
    2 A     yes       1       0.111   0.25 
    3 B     no        1       0.111   0.333
    4 B     yes       2       0.222   0.667
    5 C     no        2       0.222   1    
    

    然后用geom_col代替geom_bar绘制条形图,geom_text添加各个比例的文字标签:

    library(dplyr)
    library(ggplot2)
    
    ggplot(df_calculated, aes(x = group, y = Percent_col, fill = anon))+
      geom_col()+
      scale_y_continuous(labels=scales::percent) +
      ylab("relative frequencies")+
      geom_text(aes(label = scales::percent(Percent)), position = position_stack(0.5))+
      geom_text(inherit.aes = FALSE, 
                data = df_calculated %>% 
                  group_by(group) %>% 
                  summarise(Sum = sum(Percent_col)),
                aes(label = scales::percent(Sum), 
                    y = Sum, x = group), vjust = -0.5)
    

    它回答了你的问题吗?

    【讨论】:

    • 这解决了我的问题。仅仅因为我不太熟悉在 ggplot 之外计算这些比例,是否有可能在每个列的顶部额外添加每个列的百分比?
    • 你想要每组的百分比吗? (例如 A 为 44,44,B 为 33,33,C 为 22.22?)或者您是否希望条形图中显示的当前百分比位于每个是/否列的顶部?
    • 每组的百分比(A 为 44,44,B 为 33,33,C 为 22,22)
    • 好的,请看我更新的答案。让我知道它是否是您正在寻找的。​​span>
    • 不客气 ;) 在我看来,在外面执行计算更容易,因为它允许您验证计算是否正确。尤其是当您有多个组要计算时,我想说在ggplot2 之外更容易。但是,我认为有些人更喜欢使用..count..,但我不太擅长。
    猜你喜欢
    • 2017-04-24
    • 1970-01-01
    • 1970-01-01
    • 2014-05-24
    • 1970-01-01
    • 1970-01-01
    • 2017-04-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多