简体   繁体   中英

How to change the color of clusters using R?

I am using the R for Kmeans Clustering, so I load the library (fpc), and using plotcluster method to plot the data.

clus <- kmeans(data, centers = 5)
plotcluster(data, clus$cluster, pch = clus$cluster)

So 5 groups of particles are plotted, but with default colors for different groups. But how can I change the colors of the particles?

For example, group 1 to some particular color and group 2 to some particular color.

There is a parameter called " col " in the plotcluster function, but I don't know how to change it.

Here is the code that I tested on RStudio running on a Mac OS X 10.10.2 with the latest installation of the fpc package.

By no means am I suggesting you use these colors, but if you add the following two parameters I think you will be able to select the colors you want:

vector of class numbers which can be coerced into integers; length must equal nrow(xd)

clvecd = c(1,2,3,4,5)

vector of colors that correspond to your clusters

col =c("blue","green","purple","red","yellow")

plotcluster(  data
            , clus$cluster
            , pch = clus$cluster
            , clvecd=c(1,2,3,4,5)
            , col=c("blue","green","purple","red","yellow"))

A bit late but hey. I had this issue today and found this solution.

clus <- kmeans(x, centers=5)
vcol <- c("blue","green","purple","red","yellow")
plotcluster(x, clus$cluster, col=vcol[clus$cluster])

NB :
If length(vcol) - centers = 1, last color won't be used.
If centers - length(vcol) = 1, points in last cluster won't display.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM