如何在ggplot2中制作置信区间极限的虚线?工作室R

问题描述 投票:0回答:2

enter image description here

ggplot(data=Dane, aes(x=reg$fitted.values, y=reg$residuals))+ 
geom_smooth(method="lm", se=TRUE, level=0.95)+ 
theme(panel.background = element_rect(fill = "white", colour = "grey50"))+ 
geom_point()
r ggplot2
2个回答
5
投票

以下将使用内置数据集

iris
的子集,以及
Species == "setosa"

请注意,为了获得预测的置信带,必须在绘图之前拟合线性模型。

library(ggplot2)

data(iris)

subdf <- iris[iris$Species == "setosa", ]

pred <- predict(lm(Sepal.Width ~ Sepal.Length, subdf), 
                se.fit = TRUE, interval = "confidence")
limits <- as.data.frame(pred$fit)

ggplot(subdf, aes(x = Sepal.Length, y = Sepal.Width)) +
  geom_point() +
  theme(panel.background = element_rect(fill = "white", 
                                       colour = "grey50"))+
  geom_smooth(method = "lm") +
  geom_line(aes(x = Sepal.Length, y = limits$lwr), 
            linetype = 2) +
  geom_line(aes(x = Sepal.Length, y = limits$upr), 
            linetype = 2)


0
投票

您也可以使用绘图过程中生成的数据来完成此操作。

理想情况下,您可以使用

after_stat
函数来执行此操作,但我还没有弄清楚这部分 这篇博文有详细且有用的描述。

# basic iris
library(tidyverse)
pl_iris <- 
  iris %>% 
  filter(Species == "setosa") %>% 
  ggplot(aes(Sepal.Length, Sepal.Width )) +
  geom_point() +
  # i'm hiding the shading 
  geom_smooth(method="lm", se=T, fill = "transparent", alpha=0)

pl_iris
#> `geom_smooth()` using formula = 'y ~ x'

# layer_data(pl_iris, i=1) %>% head()
layer_data(pl_iris, i=2) %>% head()
#> `geom_smooth()` using formula = 'y ~ x'
#>          x        y     ymin     ymax         se flipped_aes PANEL group
#> 1 4.300000 2.864239 2.699618 3.028860 0.08187537       FALSE     1    -1
#> 2 4.318987 2.879401 2.718328 3.040474 0.08011048       FALSE     1    -1
#> 3 4.337975 2.894563 2.737018 3.052107 0.07835557       FALSE     1    -1
#> 4 4.356962 2.909725 2.755687 3.063762 0.07661133       FALSE     1    -1
#> 5 4.375949 2.924887 2.774333 3.075440 0.07487850       FALSE     1    -1
#> 6 4.394937 2.940049 2.792955 3.087142 0.07315789       FALSE     1    -1
#>    colour        fill linewidth linetype weight alpha
#> 1 #3366FF transparent         1        1      1     0
#> 2 #3366FF transparent         1        1      1     0
#> 3 #3366FF transparent         1        1      1     0
#> 4 #3366FF transparent         1        1      1     0
#> 5 #3366FF transparent         1        1      1     0
#> 6 #3366FF transparent         1        1      1     0

# using Layer_data
pl_iris +  
  geom_line(data=layer_data(pl_iris, i=2),
            aes(x =x, y = ymin), 
            linetype=2) +
  geom_line(data=layer_data(pl_iris, i=2),
            aes(x =x, y = ymax), 
            linetype=2)
#> `geom_smooth()` using formula = 'y ~ x'
#> `geom_smooth()` using formula = 'y ~ x'
#> `geom_smooth()` using formula = 'y ~ x'

创建于 2024-04-04,使用 reprex v2.1.0

© www.soinside.com 2019 - 2024. All rights reserved.