coding error when using abline to add linear regression lines to each set of points in a scatterplot

Viewed 101

I could use some help for:

  • adding the correct "best fit line", aka, ablineto my plot

I have a two level factor variable called "Control", with corresponding data points in the column "consumption_mean"

I plot the two here, but try to add an ablineand it does not yield the result I'm looking for at all (even the col=does not seem to work. I set it to red, it yields black.

Any help is much appreciated

I would like a red regression line through the red data points (when Control==1), and a black one through the black data points (when Control==0)

df_mean <- read.table("https://pastebin.com/raw/C2dz6bDT", header = T)

df_mean$Control <- as.factor(df_mean$Control)

plot(df_mean$mean_consumption~df_mean$day, type="n")
points(df_mean$day[df_mean$Control=='1'],df_mean$mean_consumption[df_mean$Control=='1'],col='red',pch=15,cex=.8)
points(df_mean$day[df_mean$Control=='0'],df_mean$mean_consumption[df_mean$Control=='0'],col='black',pch=15,cex=.8)
abline(lm(df_mean$mean_consumption~df_mean$day+(df_mean$Control=='1'),lwd=1,lty=1,col="red"))
abline(lm(df_mean$mean_consumption~df_mean$day+(df_mean$Control=='0'),lwd=1,lty=1,col="black"))

Notice that not only are the lines not red, but the first regression, which is set for Control==1, actually doesn't fit the red points at all.

1 Answers

Couple of things here,

1) Your lines are not turning red because you put the col and other arguments into the lm instead of the abline this can be fixed by moving one of the brackets.

abline(lm(df_mean$mean_consumption~df_mean$day+(df_mean$Control=='1')),lwd=1,lty=1,col="red")

2) Your lines and data points are not aligned because you are using different 'formulas' to plot them. your code should be similar to:

plot(x,y)
abline(lm(y ~ x))

For your case,

x = df_mean$day[df_mean$Control=='1']; and
y = df_mean$mean_consumption[df_mean$Control=='1']

so your abline should be

abline(lm(df_mean$mean_consumption[df_mean$Control=='1']~df_mean$day[df_mean$Control=='1']),lwd=1,lty=1,col="red")

After fixing all of the issues, you will get your desired plot:

Desired Plot

Related