In a dataset, I want to take two attributes and create supervised scatter plot. Does anyone know how to give different color to each class ?
I am trying to use col == c("red","blue","yellow")
in the plot command but not sure if it is right as if I include one more color, that color also comes in the scatter plot even though I have only 3 classes.
Thanks
Change R base plot point shapes You can change this to pch = 19 (solid circle) or to pch = 21 (filled circle). To change the color and the size of points, use the following arguments: col : color (hexadecimal color code or color name). For example, col = "blue" or col = "#4F6228" .
If you have a grouping variable you can create a scatter plot by group passing the variable (as factor) to the col argument of the plot function, so each group will be displayed with a different color.
In R, colors can be specified either by name (e.g col = “red”) or as a hexadecimal RGB triplet (such as col = “#FFCC00”). You can also use other color systems such as ones taken from the RColorBrewer package.
Here is an example that I built based on this page.
library(e1071); library(ggplot2) mysvm <- svm(Species ~ ., iris) Predicted <- predict(mysvm, iris) mydf = cbind(iris, Predicted) qplot(Petal.Length, Petal.Width, colour = Species, shape = Predicted, data = iris)
This gives you the output. You can easily spot the misclassified species from this figure.
Here is a solution using traditional graphics (and Dirk's data):
> DF <- data.frame(x=1:10, y=rnorm(10)+5, z=sample(letters[1:3], 10, replace=TRUE)) > DF x y z 1 1 6.628380 c 2 2 6.403279 b 3 3 6.708716 a 4 4 7.011677 c 5 5 6.363794 a 6 6 5.912945 b 7 7 2.996335 a 8 8 5.242786 c 9 9 4.455582 c 10 10 4.362427 a > attach(DF); plot(x, y, col=c("red","blue","green")[z]); detach(DF)
This relies on the fact that DF$z
is a factor, so when subsetting by it, its values will be treated as integers. So the elements of the color vector will vary with z
as follows:
> c("red","blue","green")[DF$z] [1] "green" "blue" "red" "green" "red" "blue" "red" "green" "green" "red"
You can add a legend using the legend
function:
legend(x="topright", legend = levels(DF$z), col=c("red","blue","green"), pch=1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With