简体   繁体   中英

Why is fullrange=TRUE not working for geom_smooth in ggplot2?

I have a plot where I am plotting both the linear regressions for each level of a variable as well as the linear regression for the total sample.

library(ggplot2);library(curl)
df<-read.csv(curl("https://raw.githubusercontent.com/megaraptor1/mydata/main/example.csv"))df$group<-as.factor(df$group)
ggplot(df,aes(x,y))+
  geom_point(size=2.5,shape=21,aes(fill=group),col="black")+
  geom_smooth(formula=y~x,aes(col=group,group=group),method="lm",size=1,se=F)+
  geom_smooth(formula=y~x,method="lm",col="black",size=1,fullrange=T,se=F)+
  theme_classic()+
  theme(legend.position = "none")  

在此处输入图像描述

I am trying to extend the black line (which represents all specimens) to span the full range of the axes using the command fullrange=T. However, I have found the command fullrange=T is not working on this graph regardless of what I try. This is especially strange as I have not called any limits for the graph or set any additional global factors.

This question was the closest I was able to find to my current problem, but it does not appear to be describing the same issue because that issue had to do with how the limits of the graph were called.

This seems a bit heavy handed but allows you to extent your regression line to whatever limits you choose for the x axis.

The argument fullrange is not really documented very helpfully. If you have a look at http://www.mosaic-web.org/ggformula/reference/gf_smooth.html it appears that "fullrange" applies to the points in the dataframe that is used to generate the regression line. So in your case your regression line is extending to the "fullrange". It's just that your definition of "fullrange" is not quite the same as that used by geom_smooth .

library(ggplot2)
library(dplyr)
library(curl)

lm_formula <- lm(formula = y~x, data = df)

f_lm <- function(x){lm_formula$coefficients[1] + lm_formula$coefficients[2] * x}

df_lim <- 
  data.frame(x = c(0, 5)) %>% 
  mutate(y = f_lm(x))

ggplot(df,aes(x,y))+
  geom_point(size=2.5,shape=21,aes(fill=group),col="black")+
  geom_smooth(formula=y~x,aes(col=group,group=group),method="lm",size=1,se=F)+
  geom_line(data = df_lim)+
  coord_cartesian(xlim = df_lim$x, ylim = df_lim$y, expand = expansion(mult = 0))+
  theme_classic()+
  theme(legend.position = "none") 

data

df<-read.csv(curl("https://raw.githubusercontent.com/megaraptor1/mydata/main/example.csv"))
df$group<-as.factor(df$group)

Created on 2021-04-05 by the reprex package (v1.0.0)

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