尝试使用距质心的马氏距离作为异常值(分数较高的可以分配较暗的颜色,而不是使用 alpha 值):
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')