R作图和聚类的一些脚本

hc <- read.table("c:/test.txt", header=TRUE) // hc的数据类型为list test为数据

作图:

x <- rnorm(10)

y <- rnorm(10)

#R 作图颜色~

SetTextContrastColor <- function(color)

{

ifelse( mean(col2rgb(color)) > 127, "black", "white")

}

TextContrastColor <- unlist( lapply(colors(), SetTextContrastColor) )

colCount <- 25

rowCount <- 27

plot(c(1,colCount), c(0, rowCount), type="n", ylab="", xlab="", 

axes=FALSE, ylim=c(rowCount,0))

title("R colors")

for (j in 0:(rowCount-1))

{

base <- j*colCount

remaining <- length(colors()) - base

RowSize <- ifelse(remaining < colCount, remaining, colCount)

rect((1:RowSize)-0.5, j-0.5, (1:RowSize)+0.5, j+0.5,

border="black",

col=colors()[base + (1:RowSize)])

text((1:RowSize), j, paste(base + (1:RowSize)), cex=0.7,

col=TextContrastColor[base + (1:RowSize)])

}

算法:

kmeans聚类分析

cl <- kmeans(hc[2],3) //3为聚类的个数,cl是list类型的,cl$cluster得到的是聚类结果,数据类型为integer。

barplot(cl$cluster,col=cl$cluster,xpd=FALSE, ylim=c(0:1),space=0, border=0, axes=0)

hclust 方法有多种

cl <- hclust(dist(hc[2]),"ave") //dist为hc的距离的函数,"ave"平均距离算法

memb <- cutree(cl, k=3) // cutree为把聚类结果进行处理分割成小类,k即为需要的类数

barplot(memb,col=memb,xpd=FALSE, ylim=c(0:1),space=0, border=0, axes=0)

barplot作图时颜色的设定

for (j in 0:(length(memb)))

{

colset[j] <- colors()[2/6+j*memb[j]]

}

kmeans脚本

hc <- read.table("c:/1.txt", header=TRUE)

cl <- kmeans(hc[2],3)

cl$cluster

#png("c:/1.png",height=480,width=480)

layout(matrix(1:2,2,1),heights = c(2,1))

plot(hc)

lines(hc)

palette(c("olivedrab1", "olivedrab2", "olivedrab3", "chartreuse", "chartreuse2", "chartreuse3", "deepskyblue", "deepskyblue2", "dodgerblue", "navy"))

barplot(cl$cluster,col=cl$cluster*10/3,xpd=FALSE, ylim=c(0:1),space=0, border=0, axes=0)

#dev.off()

#hclust脚本

hc <- read.table("c:/222.txt", header=TRUE)

cl <- hclust(dist(hc[2]),method="complete") 

memb <- cutree(cl, k=5)

#png("c:/1.png",height=480,width=480)

#win.metafile(filename="c:/image_path/1.emf", width=7, heights=42)

layout(matrix(1:2,2,1),heights = c(3,1))

plot(hc,xlab="", ylab="")

title("type of clust", font.main=1, adj=0)

lines(hc)

palette(c("olivedrab1", "olivedrab2", "olivedrab3", "chartreuse", "chartreuse2", "chartreuse3", "deepskyblue", "deepskyblue2", "dodgerblue", "navy"))

barplot(memb,col=memb*10/10,xpd=FALSE, ylim=c(0:1),space=0, border=0, axes=0)

posted @ 2011-07-29 09:39  magicyang1987  阅读(911)  评论(0)    收藏  举报