将文本标签添加到geom_smooth中线 [英] add text labels to geom_smooth mean lines
本文介绍了将文本标签添加到geom_smooth中线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在每个组的平均行上方添加文本标签(不更改数据框)?
How do I add text labels above each group's mean line (without changing the dataframe)?
library(ggplot2)
set.seed(1)
#toy data
data = data.frame(month=rep(seq(1,12),2),year = as.factor(c(rep(2019,12),rep(2020,12))),val = c(runif(12,80,100),runif(12,10,30)))
ggplot(data,aes(x=month,y=val,color=year))+
geom_point()+
geom_line()+
stat_smooth(method="lm",formula = y~1,se=T)
推荐答案
我将创建一个包含均值的中间数据集,并使用 geom_text
将其显示在图上
I would create an intermediate dataset holding the means and use geom_text
to display it on the plot
means <- aggregate(val ~ year, data = data, mean)
ggplot(data,aes(x=month,y=val,color=year))+
geom_point()+
geom_line()+
geom_smooth(method="lm", formula = y~1, se=T) +
geom_text(aes(x = 7, y = val+5, label = round(val, 2), color = year), data = means) # You can change the rounding, the + value or the x position
有点麻烦,因为您必须设置一些值,对于一次性绘图来说效果很好
It's kinda hacky since you have to set some values, by works fine for one-off plots
这篇关于将文本标签添加到geom_smooth中线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文