contour
(기본 R)에 해당하는 내용을 ggplot2로 플로팅하려면 어떻게해야합니까?ggplot2를 사용하여 의사 결정 경계를 표시 하시겠습니까?
require(MASS)
iris.lda<-lda(Species ~ Sepal.Length + Sepal.Width + Petal.Length + Petal.Width, data = iris)
datPred<-data.frame(Species=predict(iris.lda)$class,predict(iris.lda)$x) #create data.frame
#Base R plot
eqscplot(datPred[,2],datPred[,3],pch=as.double(datPred[,1]),col=as.double(datPred[,1])+1)
#Create decision boundaries
iris.lda2 <- lda(datPred[,2:3], datPred[,1])
x <- seq(min(datPred[,2]), max(datPred[,2]), length.out=30)
y <- seq(min(datPred[,3]), max(datPred[,3]), length.out=30)
Xcon <- matrix(c(rep(x,length(y)),
rep(y, rep(length(x), length(y)))),,2) #Set all possible pairs of x and y on a grid
iris.pr1 <- predict(iris.lda2, Xcon)$post[, c("setosa","versicolor")] %*% c(1,1) #posterior probabilities of a point belonging to each class
contour(x, y, matrix(iris.pr1, length(x), length(y)),
levels=0.5, add=T, lty=3,method="simple") #Plot contour lines in the base R plot
iris.pr2 <- predict(iris.lda2, Xcon)$post[, c("virginica","setosa")] %*% c(1,1)
contour(x, y, matrix(iris.pr2, length(x), length(y)),
levels=0.5, add=T, lty=3,method="simple")
#Eqivalent plot with ggplot2 but without decision boundaries
ggplot(datPred, aes(x=LD1, y=LD2, col=Species)) +
geom_point(size = 3, aes(pch = Species))
ggplot와 등고선 플롯 할 때, 매트릭스를 사용하는 것이 가능하지 않다 : 이하 선형 판별 함수를 분석 한 예이다. 상기 매트릭스는 용융물을 사용하여 데이터 프레임으로 재배치 될 수있다. 아래의 데이터 프레임에서 iris.pr1의 확률 값은 다음 두 열의 x 및 y 좌표와 함께 첫 번째 열에 표시됩니다. x와 y 좌표는 30 x 30 포인트의 그리드를 형성합니다.
df <- transform(melt(matrix(iris.pr1, length(x), length(y))), x=x[X1], y=y[X2])[,-c(1,2)]
I의 사후 확률은 0.5 (즉, 결정 입계) 인 좌표 (바람직 평활화 곡선에 의해 접속)을 플롯하고 싶다.
선을 그리려면 등고선 플롯을 통과해야합니까? geom_line을 사용하는 다른 방법은 없습니까? – user3236841