Heterogeneity
那就不知道了,我来自己做个稍微复杂点的。
library(tidyverse)
new_iris <- mutate(iris,id = sample(c("A","B","C"),150,replace = TRUE))
tags <- data.frame(x = rep(-Inf,9),
y = rep(Inf,9),
labels = paste0("(",letters[1:9],")"),
Species = rep(unique(iris$Species),each=3),
id = rep(c("A","B","C"),3))
p <- as_tibble(new_iris) %>%
gather(indicator, measurement, -Species,-id) %>%
ggplot(aes(indicator, measurement))+geom_boxplot()+facet_grid(Species~id)
p +
geom_text(data = tags,mapping =aes(x,y,label = labels),
hjust = -0.5, vjust = 1.5, fontface = 'plain', family = 'serif', inherit.aes = FALSE)
这个的原理其实就是需要构造一个dataframe, 里面有x
,y
,label
以及和你facet
所对应的的index,
比如我的这个tags
tags <- data.frame(x = rep(-Inf,9),
y = rep(Inf,9),
labels = paste0("(",letters[1:9],")"),
Species = rep(unique(iris$Species),each=3),
id = rep(c("A","B","C"),3))
tags
#> x y labels Species id
#> 1 -Inf Inf (a) setosa A
#> 2 -Inf Inf (b) setosa B
#> 3 -Inf Inf (c) setosa C
#> 4 -Inf Inf (d) versicolor A
#> 5 -Inf Inf (e) versicolor B
#> 6 -Inf Inf (f) versicolor C
#> 7 -Inf Inf (g) virginica A
#> 8 -Inf Inf (h) virginica B
#> 9 -Inf Inf (i) virginica C
正好有Species
和 id
列,可以一一对应每一个分面。
x
,y
是控制label在图片的位置,Inf
和-Inf
一般是控制出现在角落位置。
至于flip之后,我的猜想是x
和y
其实对调了,所以你传入geom_text
的时候需要反过来,如下
p_flip <- as_tibble(new_iris) %>%
gather(indicator, measurement, -Species,-id) %>%
ggplot(aes(indicator, measurement))+geom_boxplot()+facet_grid(Species~id)+coord_flip()
p_flip +
geom_text(data = tags,mapping =aes(y,x,label = labels),
hjust = -0.5, vjust = 1.5, fontface = 'plain', family = 'serif', inherit.aes = FALSE)
你发的这个的函数的功能,其实就是帮你生成了这个tags
dataframe
,你可以试试手动构建这个dataframe, 记住一个分面对应一行就行了。