2016-12-07 126 views
0

我想平滑geom_lines並填充它們之間的區域。我試過stat_smooth()來平滑線條,並且geom_ribbon()和geom_polygon()都沒有成功。ggplot2:平滑並填充

雙桶問題的道歉。

Smooth and fill

bell <- data.frame(
       month = c("Launch","1st","2nd","3rd","4th","5th","6th","7th","8th","9th","10th","11th","12th"), 
       rate = c(0,.05,.12,.18,.34,.42,.57,.68,.75,.81,.83,.85,.87)) 
bell$month <- factor(bell$month, levels = rev(c("Launch","1st","2nd","3rd","4th","5th","6th","7th","8th","9th","10th","11th","12th"))) 

ggplot() + 
     theme_minimal() + 
     coord_flip() + 
     scale_fill_manual(values=cols) + 
     geom_line(data=bell, aes(x=month, y=.5-(rate/2), group=1), color='pink', size=1) + 
     geom_line(data=bell, aes(x=month, y=.5+(rate/2), group=1), color='pink', size=1) + 
     theme(legend.position='none', axis.ticks=element_blank(), axis.text.x=element_blank(),axis.title.x=element_blank()) 

回答

1

一種選擇是計算loess迴歸點ggplot之外,然後將它們用geom_line(對於線)或geom_area用於填充區域(geom_areageom_ribbon,但與積ymin固定在零)。另外,你不需要coord_flip。相反,只需切換您的xy映射。無論如何,如果你想在曲線下方填充,這是非常必要的。

在下面的示例中,我爲迴歸創建了一個數字月份變量。我還將scale_fill_manual行註釋掉,因爲您的示例不提供cols矢量,並且劇情代碼無論如何都不會生成圖例。我也註釋掉了legend.position='none'這條線,因爲它是多餘的。

bell$month.num = 0:12 

m1 = loess(rate ~ month.num, data=bell) 
bell$loess.mod = predict(m1) 

ggplot(bell, aes(y=month, group=1)) + 
    theme_minimal() + 
    #scale_fill_manual(values=cols) + 
    geom_area(aes(x=.5-(loess.mod/2)), fill='pink', size=1) + 
    geom_area(aes(x=.5+(loess.mod/2)), fill='pink', size=1) + 
    theme(#legend.position='none', 
     axis.ticks=element_blank(), 
     axis.text.x=element_blank(), 
     axis.title.x=element_blank()) 

enter image description here