對於pca , nmds, pcoa 這些排序分析來說,我們可以從圖中看出樣本的排列規則,比如分成了幾組。
為例樣本分組更加的直觀,我們可以根據實驗設計時的樣本分組情況,對屬於同一個group的樣本添加1個橢圓或者其他多邊形。
新版本的ggplot2 中提供了stat_ellipse 這個stat, 可以方便的實現上面的效果。
代碼示例:
ggplot(faithful, aes(waiting, eruptions, color = eruptions > 3)) + geom_point() + stat_ellipse(level = 0.8) + stat_ellipse(level = 0.9)
效果圖如下:

通過stat_ellipse 簡單有方便,其中的level 參數指定了擬合橢圓的路徑時的置信度,這個數值越大,橢圓覆蓋的點就越多;
這里我添加兩個橢圓,只是為了美觀,ggplot2 圖層疊加的語法使得添加多個橢圓這么方便,不得不為其設計者點贊;
在舊版本的ggplot2 中, 是沒有stat_ellipse; 而官方的開發者在新版的ggplot2 中加入了這一功能,可想而知這個應用的受歡迎程度,
除了添加橢圓,也可以使用多邊形來描述分組,也很美觀,只不過代碼沒有橢圓那么簡潔
代碼示例:
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 函數,會更加的方便。
