0

我正在尝试使用 geom_text 来标记位置 =“填充”的多面 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",从而创建一个比例图时,这不起作用,因为标签(按照说明)是“计数”值。

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

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

任何帮助将不胜感激。

谢谢你。

4

1 回答 1

0

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

另请注意,我只是使用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 包(v0.2.0)于 2018 年 8 月 16 日创建。

于 2018-08-16T18:33:48.000 回答