[R] How to shade area between lines in ggplot2
Luigi Marongiu
m@rong|u@|u|g| @end|ng |rom gm@||@com
Fri Oct 23 09:58:52 CEST 2020
Hello,
I am running SVM and showing the results with ggplot2. The results
include the decision boundaries, which are two dashed lines parallel
to a solid line. I would like to remove the dashed lines and use a
shaded area instead. How can I do that?
Here is the code I wrote..
```
library(e1071)
library(ggplot2)
set.seed(100)
x1 = rnorm(100, mean = 0.2, sd = 0.1)
y1 = rnorm(100, mean = 0.7, sd = 0.1)
y2 = rnorm(100, mean = 0.2, sd = 0.1)
x2 = rnorm(100, mean = 0.75, sd = 0.1)
df = data.frame(x = c(x1,x2), y=c(y1,y2),
z=c(rep(0, length(x1)), rep(1, length(x2))))
df$z = factor(c(rep(0, length(x1)), rep(1, length(x2))))
df[, "train"] <- ifelse(runif(nrow(df)) < 0.8, 1, 0)
trainset <- df[df$train == 1, ]
testset <- df[df$train == 0, ]
trainColNum <- grep("train", names(df))
trainset <- trainset[, -trainColNum]
testset <- testset[, -trainColNum]
head(trainset); str(df)
svm_model<- svm(z ~ .,
data = trainset,
type = "C-classification",
kernel = "linear",
scale = FALSE)
#! plot
p = ggplot(data = trainset, aes(x=x, y=y, color=z)) +
geom_point() + scale_color_manual(values = c("red", "blue"))
# show decision boundaries
w = t(svm_model$coefs) %*% svm_model$SV # %*% = matrix multiplication
slope_1 = -w[1]/w[2]
intercept_1 = svm_model$rho / w[2]
p = p + geom_abline(slope = slope_1, intercept = intercept_1)
### here we go: can I use a shaded area between these two lines? ###
p = p + geom_abline(slope = slope_1, intercept = intercept_1 - 1/w[2],
linetype = "dashed") +
geom_abline(slope = slope_1, intercept = intercept_1 + 1/w[2],
linetype = "dashed")
print(p)
```
Thank you
--
Best regards,
Luigi
More information about the R-help
mailing list