Pregunta

I wanna shade the area between the two ablines in the following code. But all i could reach was to connect the two intercepts of the abline. Is there a easy way to handle this? More complicated solutions are also very welcome!

x1s <- c(.5,1,1,2,3,3.5,     1,3.5,4,5,5.5,6)
x2s <- c(3.5,1,2.5,2,1,1.2,  5.8,3,4,5,4,1)
ys <- c(rep(+1,6),          rep(-1,6))
my.data <- data.frame(x1=x1s, x2=x2s, type=as.factor(ys))
my.data

library('e1071')
svm.model <- svm(type ~ ., data=my.data, type='C-classification', kernel='linear',scale=FALSE)

plot(my.data[,-3],col=(ys+3)/2, pch=19, xlim=c(-1,6), ylim=c(-1,6))
points(my.data[svm.model$index,c(1,2)],col="blue",cex=2) # show the support vectors

w <- t(svm.model$coefs) %*% svm.model$SV
b <- -svm.model$rho
p <- svm.model$SV

abline(a=-b/w[1,2], b=-w[1,1]/w[1,2], col="black", lty=1)
abline(a=(-b-1)/w[1,2], b=-w[1,1]/w[1,2], col="orange", lty=3)
abline(a=(-b+1)/w[1,2], b=-w[1,1]/w[1,2], col="orange", lty=3)
polygon(c(0,0), c((-b-1)/w[1,2],(-b+1)/w[1,2]), col = 'grey80', border = NA)
¿Fue útil?

Solución

The way I would do it is with function curve instead of abline in order to keep to coordinates of the path of both lines and feed them to `polygon:

c1 <- curve((-b-1)/w[1,2] - x*w[1,1]/w[1,2], from=-10, to=10, 
                              col="orange",add=TRUE,lty=3)
c2 <- curve((-b+1)/w[1,2] - x*w[1,1]/w[1,2], from=-10, to=10, 
                              col="orange",add=TRUE,lty=3)
polygon(c(c1$x,rev(c2$x)), c(c1$y, rev(c2$y)),col="grey80", border=NA)

Edit: As Julian Urbano correctly suggested, you can use par('usr') to define the values for parameters from and to automatically:

u <- par('usr')
c1 <- curve((-b-1)/w[1,2] - x*w[1,1]/w[1,2], from=u[1], to=u[2], 
                              col="orange",add=TRUE,lty=3)
c2 <- curve((-b+1)/w[1,2] - x*w[1,1]/w[1,2], from=u[1], to=u[2], 
                              col="orange",add=TRUE,lty=3)
polygon(c(c1$x,rev(c2$x)), c(c1$y, rev(c2$y)),col="grey80", border=NA)
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top