簡體   English   中英

在ggplot2下手動着色平滑線

[英]Manually shading a smoothed line under ggplot2

我正在繪制一組帶有陰影的數據,以遵循“下邊界”和“上邊界”值。 我對Est值使用stat_smooth進行了平滑處理,但無法獲得UB和LB值指定的陰影區域來遵循平滑線。 數據如下:

 Quantiles   Est    LB    UB
 0.10 -4.39 -4.80 -4.00
 0.25 -3.46 -3.72 -3.22
 0.50 -3.11 -3.29 -2.91
 0.75 -2.89 -3.15 -2.60
 0.90 -1.69 -2.21 -1.09

這是我的ggplot代碼:

ggplot(data,aes(y=Est,x=Quantiles)) + stat_smooth() + 
geom_ribbon(aes(ymin=LB,ymax=UB),alpha=0.2)

在此先感謝您的幫助!

我的理解是,您希望色帶邊界遵循平滑的曲線,而不是簡單地連接LB和UB點。 在您的情況下,stat_smooth使用黃土方法來計算平滑曲線。 您沒有足夠的數據點來使用默認的2階計算真實的平滑黃土曲線,因此loess函數返回一條曲線,該曲線穿過給定的數據數據點,使用二次平滑曲線將它們連接起來,並在警告消息中報告此情況。 。 忽略這些警告,獲得平滑功能區的一種方法是計算數據平滑點和功能區邊界,然后繪制結果,如下所示:

smooth <- data.frame(Quantiles= seq( min(data$Quantiles), max(data$Quantiles), length.out=100))
smooth$Est <- predict(loess(Est ~ Quantiles, data), newdata=smooth$Quantiles)
smooth$LB  <-  predict(loess(LB ~ Quantiles, data), newdata=smooth$Quantiles)
smooth$UB  <-  predict(loess(UB ~ Quantiles, data), newdata=smooth$Quantiles)
ggplot(data=smooth,aes(y=Est,x=Quantiles)) +  geom_line() +
    geom_ribbon(aes(ymin=LB,ymax=UB),alpha=0.2)

暫無
暫無

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

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