2014-03-28 45 views
0

我有幾個散點圖,代表我的數據的不同子集。我想找到一種方法來直觀地表示這些數據子集的重疊/不重疊。在R或Matlab中,將每組數據轉換爲一個考慮數據均值和方差的橢圓的最佳方法是什麼?我基本上想要將三個單獨的散點圖變成維恩圖,如果這是有道理的。以維恩圖解方式表示散點圖數據?

+0

對於來自不同子集的點的不同顏色如何?添加橢圓當然可以完成,但不同的顏色很容易。 –

+2

This:http://stats.stackexchange.com/questions/30788/whats-a-good-way-to-use-r-to-make-a-scatterplot-that-separates-the-data-by-trea可能是你正在尋找的 – hrbrmstr

+0

是的,這是完美的! – user1566200

回答

2

除了在Q &給出的解決方案,通過一個鏈接@hrbrmstr,它的litteral表示可以使用凸包來實現:

library(scales) #Only for the transparency effect 
data(iris) 
plot(iris$Sepal.Length, iris$Sepal.Width, type="n") 
a <- split(iris, iris$Species) #Separate the dataset by ID (here species) 
for(i in seq_along(a)){ 
    h <- chull(a[[i]]) #Compute convex hull for each group 
    h <- c(h, h[1]) 
    polygon(a[[i]][h,], col=alpha(i,.5), border=NA) #Plot it 
    } 
points(iris$Sepal.Length, iris$Sepal.Width, col=iris$Species, pch=19) #Add data points 

enter image description here

+0

當我用我的數據集嘗試這個時,我得到錯誤「在data.matrix(x)中:由強制引入的NAs」,並且產生的凸包看起來很拙劣。有任何想法嗎? – user1566200

+0

@ user1566200沒有看到您的數據,我真的不知道是什麼原因導致此問題。出乎意料的是,我認爲這是一個數據類型問題:檢查應該是數字的所有東西的確是數字,而不是字符串或因子。 – plannapus

+0

謝謝,就是這樣。有絃樂。這看起來很美。有沒有辦法使用points()添加顏色的圖例?不要在任何幫助中看到它。 – user1566200

2

您可以使用ellipse功能從橢圓包到計算橢圓上的點,對於每組數據,您將爲橢圓函數提供均值,標準差和相關性,然後將結果傳遞給lines函數以添加到散點圖。如果羣體合理正常,這將工作得很好,但如果羣體中存在強偏態,則橢圓不太適合。

另一種選擇是使用chull函數來計算包含組中所有點的複合外殼。你可以用它來繪製一個包含所有點的多邊形(有些將會觸及多邊形)。如果你想要比多邊形更曲線的東西,那麼使用xspline函數來執行繪製,而不是linespolygon。以下是一些示例代碼:

with(iris, plot(Petal.Width, Petal.Length, col=c('red','green','blue')[Species])) 

tmp <- chull(iris[ iris$Species=='setosa', c('Petal.Width','Petal.Length')]) 
xspline(iris[ iris$Species=='setosa', c('Petal.Width','Petal.Length')][tmp,], 
    border='red',open=FALSE, shape= -0.75) 

tmp <- chull(iris[ iris$Species=='versicolor', c('Petal.Width','Petal.Length')]) 
xspline(iris[ iris$Species=='versicolor', c('Petal.Width','Petal.Length')][tmp,], 
    border='green',open=FALSE, shape= -0.75) 

tmp <- chull(iris[ iris$Species=='virginica', c('Petal.Width','Petal.Length')]) 
xspline(iris[ iris$Species=='virginica', c('Petal.Width','Petal.Length')][tmp,], 
    border='blue',open=FALSE, shape= -0.75) 



library(ellipse) 

with(iris, plot(Petal.Width, Petal.Length, col=c('red','green','blue')[Species])) 

polygon(ellipse( 
    var(iris[ iris$Species=='setosa', c('Petal.Width','Petal.Length') ]), 
    centre=colMeans(iris[ iris$Species=='setosa', c('Petal.Width','Petal.Length') ]), 
    t=3), 
    border='red') 

polygon(ellipse( 
    var(iris[ iris$Species=='versicolor', c('Petal.Width','Petal.Length') ]), 
    centre=colMeans(iris[ iris$Species=='versicolor', c('Petal.Width','Petal.Length') ]), 
    t=3), 
    border='green') 

polygon(ellipse( 
    var(iris[ iris$Species=='virginica', c('Petal.Width','Petal.Length') ]), 
    centre=colMeans(iris[ iris$Species=='virginica', c('Petal.Width','Petal.Length') ]), 
    t=3), 
    border='blue')