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")
我想将 geom_line 限制在与 stat_smooth 相同的范围内(这似乎是由 xmax/xmin 定义的)。
xlim 参数没有帮助(这是提议的 here )。在实际应用中,geom_line 斜率和截距会从模型更新中提取,因此它们会略有不同。谢谢你。
最佳答案
我认为这是获得所需内容的一种方法:
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
允许您设置其域。关于r - 限制geom_line的x轴范围(由斜率和截距定义),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32226513/