簡體   English   中英

在ggplot2中僅繪制stat_smooth的邊界

[英]Drawing only boundaries of stat_smooth in ggplot2

當將stat_smooth()geom_point一起使用時,是否有一種方法可以刪除陰影擬合區域,但只能繪制其外部邊界? 我知道我可以使用以下方法刪除陰影區域:

 geom_point(aes(x=x, y=y)) + geom_stat(aes(x=x, y=y), alpha=0)

但是如何使它的外部邊界(外部曲線)仍然顯示為淡淡的黑線?

您也可以將geom_ribbonfill = NA一起使用。

gg <- ggplot(mtcars, aes(qsec, wt))+
        geom_point() +  
        stat_smooth( alpha=0,method='loess')

rib_data <- ggplot_build(gg)$data[[2]]

ggplot(mtcars)+
  stat_smooth(aes(qsec, wt), alpha=0,method='loess')+
  geom_point(aes(qsec, wt)) +  
  geom_ribbon(data=rib_data,aes(x=x,ymin=ymin,ymax=ymax,col='blue'),
                fill=NA,linetype=1) 

在此處輸入圖片說明

...如果由於某種原因您不希望使用豎線,則可以只使用兩個geom_line層:

ggplot(mtcars)+
    stat_smooth(aes(qsec, wt), alpha=0,method='loess')+
    geom_point(aes(qsec, wt)) + 
    geom_line(data = rib_data,aes(x = x,y = ymax)) + 
    geom_line(data = rib_data,aes(x = x,y = ymin))

有許多可能更簡單的方法,但是您可以先嘗試一下。 我使用ggbuild置信區間的數據,然后在geom_line使用

# create a ggplot object with a linear smoother and a CI
library(ggplot2)    
gg <- ggplot(data = mtcars, aes(x = wt, y = mpg)) +
    geom_point() +
    geom_smooth(method = "lm")
gg

# grab the data from the plot object
gg_data <- ggplot_build(gg)
str(gg_data)
head(gg_data$data[[2]])
gg2 <- gg_data$data[[2]]

# plot with 'CI-lines' and the shaded confidence area
ggplot(data = mtcars, aes(x = wt, y = mpg)) +
    geom_point() +
    geom_smooth(method = "lm", se = TRUE, size = 1) +
    geom_line(data = gg2, aes(x = x, y = ymin), size = 0.02) +
    geom_line(data = gg2, aes(x = x, y = ymax), size = 0.02)


# plot with 'CI-lines' but without confidence area
ggplot(data = mtcars, aes(x = wt, y = mpg)) +
    geom_point() +
    geom_smooth(method = "lm", se = FALSE, size = 1) +
    geom_line(data = gg2, aes(x = x, y = ymin), size = 0.02) +
    geom_line(data = gg2, aes(x = x, y = ymax), size = 0.02)

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM