我正在尝试使用geom_text标签多面的geom_col图,其中position =“ fill”。
这是我正在使用的数据的简化版本:
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”样式图,因此我有办法“访问”这些比例然后使用它们来标记我的图?
任何帮助将不胜感激。
谢谢。
答案 0 :(得分: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 package(v0.2.0)于2018-08-16创建。