一些與馬氏距離從形心嘗試此爲異常值的得分(分數越高的那些可以分配較深的顏色,而不是使用阿爾法值):
myDat <- data.frame(x=rnorm(10000,0,1),y=rnorm(10000,0,1))
mu <- colMeans(myDat)
# assuming x, y independent, if not we can always calculate a non-zero cov(x,y)
sigma <- matrix(c(var(myDat$x), 0, 0, var(myDat$y)), nrow=2)
# use (squared) *Mahalanobis distance* as outlier score
myDat$outlier.score <- apply(myDat, 1, function(x) t(x-mu)%*%solve(sigma)%*%(x-mu))
qplot(x=x, y=y, data=myDat, col=outlier.score) +
scale_color_gradient(low='white', high='blue')
# assuming x, y are not independent
sigma <- matrix(c(var(myDat$x), cov(myDat$x, myDat$y), cov(myDat$x, myDat$y), var(myDat$y)), nrow=2)
# use (squared) *Mahalanobis distance* from centroid as outlier score
myDat$outlier.score <- apply(myDat, 1, function(x) t(x-mu)%*%solve(sigma)%*%(x-mu))
qplot(x=x, y=y, data=myDat, col=outlier.score) +
scale_color_gradient(low='white', high='blue')
根據您的具體要求,您可以考慮[geom_density_2d](http://docs.ggplot2.org/current/geom_density_2d.html)。見例如第二個最後一個例子,以及[scale_fill_gradient](http://docs.ggplot2.org/current/scale_gradient.html),您可以在其中設置您所選擇的「低」和「高」顏色。 – Henrik