2013-08-10 5 views
7

Quando si utilizza stat_smooth() con geom_point esiste un modo per rimuovere l'area di adattamento ombreggiata, ma solo disegnarne i limiti esterni? So di poter rimuovere la regione ombreggiata con qualcosa di simile:Disegno solo dei limiti di stat_smooth in ggplot2

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

ma come posso fare i confini esterni di esso (curve esterne) ancora visibili come linee nere deboli?

+1

Non c'è 'geom_stat' . intendi 'stat_smooth'? – agstudy

+0

come da OP, dovrebbe essere 'c + stat_smooth (fill =" grey50 ", size = 2, alpha = 0)' – Metrics

+1

C'è 'stat_smooth' o' geom_smooth'. – seancarmody

risposta

11

È inoltre possibile utilizzare geom_ribbon con fill = 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) 

enter image description here

... e se per qualche motivo non si desidera che le barre verticali, si può semplicemente utilizzare due strati: 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)) 
+1

Spero non ti dispiaccia modificare ... solo consolidando le cose nella risposta superiore. – joran

+0

@joran sei sempre il benvenuto! – agstudy

8

Ci sono probabilmente dei modi più semplici, ma puoi provarlo all'inizio. Afferro i dati per l'intervallo di confidenza con ggbuild, che ho poi usare in 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) 

enter image description here