ggplot2: Problem with x axis when adding regressio

2020-02-06 16:43发布

Based on the example here Adding Regression Line Equation and R2 on graph, I am struggling to include the regression line equation for my model in each facet. However, I don't figure why is changing the limits of my x axis.

library(ggplot2)
library(reshape2)

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"))


ggplot(data = df, mapping = aes(x = year, y = value)) +
geom_point() +
scale_x_continuous() + 
stat_smooth_func(geom = 'text', method = 'lm', hjust = 0, parse = T) +
geom_smooth(method = 'lm', se = T) +
facet_wrap(~ variable) # as you can see, the scale_x_axis goes back to 1800

If I include on the x the limits,

scale_x_continuous(limits = c(1979,2010)) 

it does not show the regression coefficient anymore. What am I doing wrong here?

stat_smooth_func available here: https://gist.github.com/kdauria/524eade46135f6348140

2条回答
smile是对你的礼貌
2楼-- · 2020-02-06 17:24

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)

查看更多
SAY GOODBYE
3楼-- · 2020-02-06 17:30

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 belowenter image description here

查看更多
登录 后发表回答