在使用分面 geom_col 和位置 ="fill" 时为 geom_text 创建比例数字

Creating proportional figures for geom_text, when using faceted geom_col, and position="fill"

我正在尝试使用 geom_text 标记位置 ="fill".

的多面 geom_col 图

这是我使用的数据的简化版本:

group = c("Group1", "Group1", "Group1", "Group1", "Group1", "Group1","Group2", "Group2", "Group2", "Group2", "Group2", "Group2")

year = c("Year1", "Year2", "Year3", "Year1", "Year2", "Year3", "Year1", "Year2", "Year3", "Year1", "Year2", "Year3")

gender = c("Male", "Male", "Male", "Female", "Female", "Female", "Male", "Male", "Male", "Female", "Female", "Female")

count = c(15, 16, 20, 12, 13, 13, 21, 24, 25, 27, 23, 30)

data = as.data.frame(cbind(group, year, gender, as.integer(count)))

现在,在使用 geom_line 时这样做非常简单:

data %>%
  ggplot(aes(year, count, color=gender, group=gender))+
  geom_point(size=2.5)+
  geom_line(size=1.5)+
  facet_wrap(~group)+
  geom_label(label=count)

但是,当使用 geom_col 和 position="fill",从而创建比例图时,这不起作用,因为标签(按照说明)是 'count' 值.

data %>%
  ggplot(aes(year, count, fill=gender))+
  geom_col(position="fill")+
  facet_wrap(~group)+
  geom_label(label=count)

我的问题是,由于 ggplot 能够生成比例以创建 geom_col-position="fill" 样式图,我有办法 'access'这些比例然后用它们来标记我的情节?

如有任何帮助,我们将不胜感激。

谢谢。

您只需进行几步预处理即可计算每个组的份额,然后将其用于定位条和制作标签。

另请注意,我仅使用 data.frame 而不是 as.data.frame(cbind()) 来将 count 保持为数字而不是因子。

通过按年和组分组,我可以计算这些组组合中每种性别的比例。

library(tidyverse)

...

data <- data.frame(group, year, gender, count)

data_props <- data %>%
  group_by(year, group) %>%
  mutate(prop = round(count / sum(count), digits = 2)) 

data_props
#> # A tibble: 12 x 5
#> # Groups:   year, group [6]
#>    group  year  gender count  prop
#>    <fct>  <fct> <fct>  <dbl> <dbl>
#>  1 Group1 Year1 Male      15  0.56
#>  2 Group1 Year2 Male      16  0.55
#>  3 Group1 Year3 Male      20  0.61
#>  4 Group1 Year1 Female    12  0.44
#>  5 Group1 Year2 Female    13  0.45
#>  6 Group1 Year3 Female    13  0.39
#>  7 Group2 Year1 Male      21  0.44
#>  8 Group2 Year2 Male      24  0.51
#>  9 Group2 Year3 Male      25  0.45
#> 10 Group2 Year1 Female    27  0.56
#> 11 Group2 Year2 Female    23  0.49
#> 12 Group2 Year3 Female    30  0.55

ggplot(data_props, aes(x = year, y = prop, fill = gender)) +
  geom_col(position = "stack") +
  geom_label(aes(label = prop), position = position_stack(vjust = 0.5)) +
  facet_wrap(~ group)

reprex package (v0.2.0) 创建于 2018-08-16。