對於pca , nmds, pcoa 這些排序分析來講,咱們能夠從圖中看出樣本的排列規則,好比分紅了幾組。函數
爲例樣本分組更加的直觀,咱們能夠根據實驗設計時的樣本分組狀況,對屬於同一個group的樣本添加1個橢圓或者其餘多邊形。設計
新版本的ggplot2 中提供了stat_ellipse 這個stat, 能夠方便的實現上面的效果。code
代碼示例:blog
ggplot(faithful, aes(waiting, eruptions, color = eruptions > 3)) + geom_point() + stat_ellipse(level = 0.8) + stat_ellipse(level = 0.9)
效果圖以下:排序
經過stat_ellipse 簡單有方便,其中的level 參數指定了擬合橢圓的路徑時的置信度,這個數值越大,橢圓覆蓋的點就越多;ip
這裏我添加兩個橢圓,只是爲了美觀,ggplot2 圖層疊加的語法使得添加多個橢圓這麼方便,不得不爲其設計者點贊;開發
在舊版本的ggplot2 中, 是沒有stat_ellipse; 而官方的開發者在新版的ggplot2 中加入了這一功能,可想而知這個應用的受歡迎程度,it
除了添加橢圓,也能夠使用多邊形來描述分組,也很美觀,只不過代碼沒有橢圓那麼簡潔io
代碼示例:function
library(ggplot2) library(plyr) ggplot(faithful, aes(waiting, eruptions, color = eruptions > 3)) + geom_point() + stat_ellipse() # faithful # x y group # 1 2 1 # 1 3 1 # 2 5 2 # 1 3 2 faithful$group <- 1 faithful$group[data$eruptions > 3] <- 2 find_hull <- function(df) df[chull(df[[1]], df[[2]]), ] hulls <- ddply(faithful, "group", find_hull) ggplot(faithful, aes(waiting, eruptions, color = eruptions > 3)) + geom_point() + geom_polygon(data = hulls, alpha = 0.5, aes(fill = factor(group)),show.legend = F)
效果圖以下:
因爲沒有內置的stat 函數,因此添加了許多代碼來計算對應的多邊形的路徑,若是將其寫成對應的stat 函數,會更加的方便。