2012-11-03 38 views
11

我有這個ggplotSmoothing在ggplot

ggplot(dt.1, aes(x=pctOAC,y=NoP, fill=Age)) + 
    geom_bar(stat="identity",position=position_dodge()) + 
    geom_smooth(aes(x=pctOAC,y=NoP, colour=Age), se=F, method="loess",show_guide = FALSE,lwd=0.7) + 
    theme(legend.position=c(.2,0.8)) 

enter image description here

dt1 <- structure(list(Age = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("o80", "u80"), class = "factor"), NoP = c(47L, 5L, 33L, 98L, 287L, 543L, 516L, 222L, 67L, 14L, 13L, 30L, 1L, 6L, 17L, 30L, 116L, 390L, 612L, 451L, 146L, 52L), pctOAC = c(0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100)), .Names = c("Age", "NoP", "pctOAC"), row.names = c(NA, -22L), class = "data.frame") 

我想有流暢的線條約束在零以上,或許類似於核密度的東西。事實上,如果我底層數據,我預計內核密度是剛好我想要的,但我只有聚合的數據。有沒有辦法做到這一點?我嘗試在geom_smooth中使用不同的method=,但小數據集似乎阻止了它。我想知道如何使用stat_function,但是我不知道如何繼續尋找合適的功能進行繪圖。

+0

是不是有geom_density ??? –

回答

14

另一種可能性是使用method="glm"與樣條曲線和日誌鏈接(即也試過method="gam",但其自動複雜性調整要減少wiggliness太多:

library(splines) 
ggplot(dt.1, aes(x=pctOAC,y=NoP, fill=Age)) + 
    geom_bar(stat="identity",position=position_dodge()) + 
    geom_smooth(aes(colour=Age), se=F, 
       method="glm", 
       formula=y~ns(x,8), 
       family=gaussian(link="log"), 
       show_guide = FALSE,lwd=0.7) + 
    theme(legend.position=c(.2,0.8)) 

enter image description here

+0

這真是太棒了!!!!! +1 –

4

geom_density()怎麼樣?

ggplot(dt1, aes(x=pctOAC,y=NoP, colour=Age, fill=Age)) + 
    geom_bar(stat="identity",position=position_dodge()) + 
    geom_density(stat="identity", fill=NA) + 
    theme(legend.position=c(.2,0.8)) 

enter image description here

+1

它確實不是看起來這實際上是平滑的?儘管如此,即使只是插值,有沒有什麼辦法可以說服'ggplot2'在中間點進行評估,相當於'density'中的'n'參數? –

+0

回想起來我認爲'stat_identity'沒有使'geom_density'有意義 –