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

标签 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 斜率和截距会从模型更新中提取,因此它们会略有不同。谢谢你。

最佳答案

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

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

关于r - 限制geom_line的x轴范围(由斜率和截距定义),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32226513/

相关文章:

r - 如何重置 R 中的 'par' (pty ='s') 值

r - 如何使用 tidyverse : tibble, purrr, dplyr 在列表列上设置名称

r - 在 Shiny 的应用程序中缓存基本 ggplot 并允许动态修改图层(与 ggplot 等效的leafletProxy)

r - ggplot2 & stat_ellipse : Draw ellipses around multiple groups of points

r - 如何控制 ggplot fiddle 图(点)中的透明度(alpha)

r - 如何在一张图中绘制 Gamma 分布的拟合图和实际图?

r - 有没有一种方法可以创建一个在 %>% 内的 mutate 中使用的函数

r - 如何使用 facet_wrap 将 y 轴设置为等于 x 轴 geom_line

regex - 如何使用R从一行中提取多个字符串

r - ggplot2 R 上的连续到离散图例