如何在 ggplot 中添加统计值?

How can i add statistical values in a ggplot?

对于我的硕士论文,我需要创建 5 个多图,每个图包含 12 个散点图。我需要添加统计值 RMSE、MAE 和 MBE。 这些情商。是:

rmse(sim, obs, na.rm = TRUE)
mae(sim, obs, na.rm = TRUE)
mean((sim - obs), na.rm = TRUE)

我需要在绘图中自动添加这些值。我的代码是:

ggplot(data=Bad_Lauchstaedt, mapping=aes(x= `one_h_gap_L`, y= `BL 2-1`))+
  geom_smooth(method = "lm",se=FALSE, color="red")+
  geom_abline(intercept = 0, slope = 1, color="darkgray", size=1.2)+
  geom_point(color="darkblue", shape=1)+
  labs(y="measured data", x="gap filled data by lysimeters", title = "best fit lysimeters")+
  theme_bw()+
  theme(plot.title = element_text(hjust = 0.5, size = 20))+
  theme(axis.title.x = element_blank(),axis.text.x = element_blank(),axis.ticks.x = element_blank())+
  theme(axis.title.y = element_blank(),axis.text.y = element_text(size = 14), axis.ticks.y = element_blank())+
  xlim(0,0.8)+
  ylim(0,0.8)+
  theme(plot.margin = unit(c(0,0,0,0),"pt"))+
  stat_poly_eq(formula = R_sqr,
               rr.digits = 3,parse = TRUE,
               size=7)

对于我的代码,我找到了这个答案:

label <- df%>% 
  summarize(RMSE = rmse(sim, obs, na.rm = TRUE),
            MAE = mae(sim, obs, na.rm = TRUE),
            MBE = mean( (sim - obs), na.rm = TRUE)) %>%
  mutate(
    posx = 0.5, posy = 0.05,
    label = glue("RMSE = {round(RMSE, 3)} <br> MAE = {round(MAE, 3)} <br> MBE = {round(MBE, 3)} ")) 

p +
  geom_richtext(
    data = label,
    aes(posx, posy, label = label),
    hjust = 0, vjust = 0,
    size = 4,
    fill = "white", label.color = "black")