[英]Add text labels at the top of density plots to label the different groups
我有以下 ggplot 密度图
ggplot(mpg, aes(cty)) + geom_density(aes(fill=factor(cyl)))
如何删除图例,并在每个分布上方添加标签以表示它所属的组?
就像@DavidKlotz 在评论中所说的那样,必须事先计算每组cyl
的cty
密度的最大值。 我将使用 Hadley Wickham 的split/lapply/combine
策略来做到这一点。
sp <- split(mpg$cty, mpg$cyl)
a <- lapply(seq_along(sp), function(i){
d <- density(sp[[i]])
k <- which.max(d$y)
data.frame(cyl = names(sp)[i], xmax = d$x[k], ymax = d$y[k])
})
a <- do.call(rbind, a)
现在剧情。
ggplot(mpg, aes(cty)) +
geom_density(aes(fill = factor(cyl)), alpha = 0.5) +
geom_text(data = a,
aes(x = xmax, y = ymax,
label = cyl, vjust = -0.5)) +
scale_fill_discrete(guide = FALSE)
现在使用geomtextpath
包会更容易一些:
library(geomtextpath)
#> Loading required package: ggplot2
ggplot(mpg, aes(cty, fill=factor(cyl))) +
geom_density(alpha = 0.5) +
geom_textdensity(aes(label = cyl),
hjust = "ymax",
vjust = -0.5, text_only = TRUE, text_smoothing = 20) +
ylim(c(0, 0.6)) +
theme(legend.position = "none")
由reprex 包(v2.0.1)于 2022-01-18 创建
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.