Range limitation along the x axis of geom_line (defined by tilt and intercept)

library(ggplot2)
##
df <- as.data.frame(matrix(rnorm(60*2, mean=3,sd=1), 60, 2))
    colnames(df) <- c("A", "B")
    cf1 <- coef(lm(B~A, data=df))
##    
ggplot(df, aes(A,B)) +
  geom_point() +
  stat_smooth(method = "lm", color="red", fill="red", alpha=0.1, fullrange=TRUE) +
  #xlim(0,6)+
  geom_abline(intercept = cf1[1], slope = cf1[2], lty="dashed", col="green") 

Example

I want to limit geom_line to the same range as stat_smooth (which seems to be defined by xmax / xmin). The xlim argument did not help (suggested here). In a real-life application, geom_line geometry and interception will be extracted from model updates, so they will be slightly different. Thanks.

+4
source share
1 answer

I think this is one way to get what you are looking for:

min_x <- min(df$A)
min_y <- unname(cf1[1])
max_x <- max(df$A)
max_y <- min_y + unname(cf1[2]) * max_x
##
p <- ggplot(df, aes(A,B)) +
  geom_point() +
  stat_smooth(
    method = "lm", color = "red", 
    fill = "red", alpha = 0.1, 
    fullrange = TRUE)
##
R> p + geom_segment(
    aes(x = min_x, y = min_y,
        xend = max_x, yend = max_y),
    linetype = "dashed",
    color = "green")

, , , , geom_abline .

enter image description here

+4

All Articles