2016-05-23 70 views
0

我使用geom_smooth函數來繪製一組點的loess估計值以及置信區間。自定義平滑置信區間的計算方法

現在我需要改變計算置信界限的方法(即我需要改變模糊帶的形狀)。在geom_smooth有沒有辦法做到這一點?

或者,我該如何模仿ggplot2?我怎麼能這樣模糊樂隊?

回答

0

如果您需要繪製一個不屬於geom_smooth選項的東西,那麼最好的方法是自己手動調整模型。

你還沒有說你需要什麼方法。 但是,這裏是一個將黃土與家族對稱擬合併計算其標準誤差的例子。

d <- data.frame(x = rnorm(100), y = rnorm(100)) 

# The original plot using the default loess method 
p <- ggplot(d, aes(x, y)) + geom_smooth(method = 'loess', se = TRUE) 

# Fit loess model with family = 'symmetric' 
# Replace the next 2 lines with whatever different method you need 
loess_smooth <- loess(d$x ~ d$y, family = 'symmetric') 

# Predict the model over the range of data you are interested in. 
loess_pred <- predict(loess_smooth, 
         newdata = seq(min(d$x), max(d$x), length.out = 1000), 
         se = TRUE) 

loess.df <- data.frame(fit = loess_pred$fit, 
         x = seq(min(d$x), max(d$x), length.out = 1000), 
         upper = loess_pred$fit + loess_pred$se.fit, 
         lower = loess_pred$fit - loess_pred$se.fit) 

# plot to compare 
p + 
    geom_ribbon(data = loess.df, aes(x = x, y = fit, ymax = upper, ymin = lower), alpha = 0.6) + 
    geom_line(data = loess.df, aes(x = x, y = fit)) 

Two loess fits