限制geom_line的x轴范围(由斜率和截距定义)

nou*_*use 4 r ggplot2

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") 
Run Code Online (Sandbox Code Playgroud)

例

我想将geom_line限制为与stat_smooth相同的范围(似乎由xmax / xmin定义)。xlim参数没有帮助(这是在此处提出的)。在实际应用中,geom_line的斜率和截距将从模型更新中提取,因此它们会略有不同。谢谢。

nru*_*ell 5

我认为这是获得所需内容的一种方法:

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")
Run Code Online (Sandbox Code Playgroud)

在您手动计算端点坐标时,这需要一些额外的工作,而不是仅将斜率和截距值传递给函数,但这似乎geom_abline不允许您设置其域。

在此处输入图片说明