You can use the following basic syntax to plot an SVM (support vector machine) object in R:
library(e1071) plot(svm_model, df)
In this example, df is the name of the data frame and svm_model is a support vector machine fit using the svm() function.
The following example shows how to use this syntax in practice.
Example: How to Plot SVM Object in R
Suppose we have the following data frame in R that contains information about various basketball players:
#create data frame df <- data.frame(points = c(4, 5, 5, 7, 8, 12, 15, 22, 25, 29), assists = c(3, 4, 6, 8, 5, 6, 5, 6, 8, 12), good = factor(c(0, 0, 0, 1, 0, 1, 0, 1, 1, 1))) #view data frame df points assists good 1 4 3 0 2 5 4 0 3 5 6 0 4 7 8 1 5 8 5 0 6 12 6 1 7 15 5 0 8 22 6 1 9 25 8 1 10 29 12 1
Suppose we would like to create a support vector machine that uses the variables points and assists to predict whether or not a player is good (0 = no, 1 = yes).
We can use the following code to fit the support vector machine and then plot the results:
library(e1071) #fit support vector machine model = svm(good ~ points + assists, data = df) #plot support vector machine plot(model, df)
The plot displays the values for the assists variable on the x-axis, the values for the points variable on the y-axis, and uses two different colors to display whether or not a player is predicted to be good (red) or not (yellow).
Note that you can use the color.palette argument within the plot() function to use a different color palette for the plot.
For example, we might choose to use the heat.colors color palette:
library(e1071) #fit support vector machine model = svm(good ~ points + assists, data = df) #plot support vector machine using different color palette plot(model, df, color.palette = heat.colors)
Other popular choices for the color.palette argument include:
Each color palette will produce different colors for the plot.
The following tutorials explain how to perform other common tasks in R: