title: R: How to plot the hyperplane and margins of an svm in ggplot2?
body: <p>I'm following along Tibshirani's ISL text. I'm trying to plot the results of an SVM in ggplot2. I can get the points and the support vectors, but I can't figure out how to get the margins and hyperplane drawn for the 2D case. I Googled and checked the e1071 readme. A general, dynamic solution (applicable to a variety of SVM kernels,costs,etc.) would be great. Here is my MWE:</p>
  
  <pre><code>set.seed(1)
  N=20
  x=matrix(rnorm(n=N*2), ncol=2)
  y=c(rep(-1,N/2), rep(1,N/2))
  x[y==1,] = x[y==1,] + 1;x[y==1,]
  dat = data.frame(x=x, y=as.factor(y))
  library(e1071)
  library(ggplot2)
  svmfit=svm(y~., data=dat, kernel="linear", cost=10, scale=FALSE)
  
  df = dat; df
  df = cbind(df, sv=rep(0,nrow(df)))
  df[svmfit$index,]$sv = 1
  
  ggplot(data=df,aes(x=x.1,y=x.2,group=y,color=y)) +     
      geom_point(aes(shape=factor(sv)))
  </code></pre>
  
  <p>Something like this:
  <a href="https://i.stack.imgur.com/WO9Bl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WO9Bl.png" alt="enter image description here"></a>
  (From Python's scikit-learn)</p>