简体   繁体   中英

Specify regression line intercept (R & ggplot2)

BACKGROUND

My current plot looks like this:

在此输入图像描述

PROBLEM

I want to force the regression line to start at 1 for station_1.

CODE

 library(ggplot2)

 #READ IN DATA
 var_x = c(2001,2002,2003,2004,2005,2006,2007,2008,2009,2010,2011,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010,2011)
 var_y = c(1.000000,1.041355,1.053106,1.085738,1.126375,1.149899,1.210831,1.249480,1.286305,1.367923,1.486978,1.000000,0.9849343,0.9826141,0.9676000,0.9382975,0.9037476,0.8757748,0.8607960,0.8573634,0.8536138,0.8258877)
 var_z = c('Station_1','Station_1','Station_1','Station_1','Station_1','Station_1','Station_1','Station_1','Station_1','Station_1','Station_1','Station_2','Station_2','Station_2','Station_2','Station_2','Station_2','Station_2','Station_2','Station_2','Station_2','Station_2')

 df_data = data.frame(var_x,var_y,var_z)

 out = ggplot(df_data,aes(x=var_x,y=var_y,group=var_z))       
 out = out + geom_line(aes(linetype=var_z),size=1)  
 out = out + theme_classic()

 #SELECT DATA FOR Station_1
 PFI_data=subset(df_data,var_z=="Station_1")

 #PLOT REGRESSION FOR Station_1
 out = out+ stat_smooth(data = PFI_data,
                   method=lm,
                   formula = y~x,
                   se=T,size = 1.4,colour = "blue",linetype=1)

Any help would be appreciated - this has been driving me crazy for too long!

First of all, you should be careful when forcing a regression line to some fixed point. Here's a link to a discussion why.

Now, from a technical perspective, I'm relying heavily on these questions and answers: one , two . The outline of my solution is the following: precompute the desired intercept, run a regression without it, add the intercept to the resulting prediction.

I'm using an internal ggplot2:::predictdf.default function to save some typing. The cbind(df, df) part may look strange, but it's a simple hack to make geom_smooth work properly, since there are two factor levels in var_z .

# Previous code should remain intact, replace the rest with this:
# SELECT DATA FOR Station_1
PFI_data=subset(df_data,var_z=="Station_1")
names(PFI_data) <- c("x", "y", "z")

x0 <- df_data[df_data$var_z == "Station_1", "var_x"][1]
y0 <- df_data[df_data$var_z == "Station_1", "var_y"][1]

model <- lm(I(y-y0) ~ I(x-x0) + 0, data = PFI_data)
xrange <- range(PFI_data$x)
xseq <- seq(from=xrange[1], to=xrange[2])
df <- ggplot2:::predictdf.default(model, xseq, se=T, level=0.95)
df <- rbind(df, df)
df[c("y", "ymin", "ymax")] <- df[c("y", "ymin", "ymax")] + y0
out + geom_smooth(aes_auto(df), data=df, stat="identity")

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM