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

时间:2015-08-26 12:20:16

标签: 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") 

Example

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

1 个答案:

答案 0 :(得分:4)

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

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

相关问题