ggplot2: Problem with x axis when adding regression line equation on each facet

旧时模样 提交于 2019-11-28 12:53:38

You can use stat_poly_eq function from the ggpmisc package.

library(reshape2)
library(ggplot2)
library(ggpmisc)
#> For news about 'ggpmisc', please, see https://www.r4photobiology.info/
#> For on-line documentation see https://docs.r4photobiology.info/ggpmisc/

df <- data.frame(year = seq(1979,2010), M02 = runif(32,-4,6), 
                 M06 = runif(32, -2.4, 5.1), M07 = runif(32, -2, 7.1))
df <- melt(df, id = c("year"))

formula1 <- y ~ x

ggplot(data = df, mapping = aes(x = year, y = value)) +
  geom_point() +
  scale_x_continuous() + 
  geom_smooth(method = 'lm', se = TRUE) +
  stat_poly_eq(aes(label = paste(..eq.label.., ..rr.label.., sep = "~~~~")), 
               label.x = "left", label.y = "top",
               formula = formula1, parse = TRUE, size = 3) +
  facet_wrap(~ variable) 

ggplot(data = df, mapping = aes(x = year, y = value)) +
  geom_point() +
  scale_x_continuous() + 
  geom_smooth(method = 'lm', se = TRUE) +
  stat_poly_eq(aes(label = paste(..eq.label.., sep = "~~~")), 
               label.x = "left", label.y = 0.15,
               eq.with.lhs = "italic(hat(y))~`=`~",
               eq.x.rhs = "~italic(x)",
               formula = formula1, parse = TRUE, size = 4) +
  stat_poly_eq(aes(label = paste(..rr.label.., sep = "~~~")), 
               label.x = "left", label.y = "bottom",
               formula = formula1, parse = TRUE, size = 4) +
  facet_wrap(~ variable) 

Created on 2019-01-10 by the reprex package (v0.2.1.9000)

Probably someone will suggest a better solution, but as an alternative, you can change stat_smooth_func and you can make the final row like this

data.frame(x=1979, y=ypos, label=func_string)

instead of

data.frame(x=xpos, y=ypos, label=func_string)

So, the plot will be like below

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!