查看原文
其他

吉林说R图系列|第一篇:如何绘制各类图形(续上篇)

2016-09-02 王吉林 R语言中文社区

三、特殊图形

(一)心型图

> #心形

> t=c()

> for(k in 10:13){

+   for(i in 1:3000)

+     t=c(t,i*k*pi/3000)

+ }

> x=16*sin(t)^3

> y=13*cos(t)-5*cos(2*t)-2*cos(3*t)-cos(4*t)

> lb=rep(paste("真心",1:4),each=3000)

> #head(lb)

> dd=data.frame(x=x, y=y,lb=lb)

> #dim(dd)

> p=ggplot(dd, aes(x, y))+facet_wrap(~lb)+

+   geom_line(colour = rainbow(12000))+xlab("")+ylab("")+mytheme+

+   ggtitle("心形曲线图(填充颜色)\nx=16*sin(t)^3\ny=13*cos(t)-5*cos(2*t)-2*cos(3*t)-cos(4*t)")

> print(p)

 

(二)蝴蝶图

> #蝴蝶曲线

> dev.off()

> t=c()

> for(k in 10:13){

+ for(i in 1:3000)

+ t=c(t,i*k*pi/3000)

+ }

> #length(t)

> x=sin(t)*(exp(cos(t))-2*cos(4*t)-sin(t/12)^5)

> y=cos(t)*(exp(cos(t))-2*cos(4*t)-sin(t/12)^5)

>

> lb=rep(paste("类别",1:4),each=3000)

> #head(lb)

> dd=data.frame(x=x, y=y,lb=lb)

> #dim(dd)

> p=ggplot(dd, aes(x, y))+facet_wrap(~lb)+

+   geom_path(colour = rainbow(12000))+xlab("")+ylab("")+mytheme+

+   ggtitle("蝴蝶曲线\nx=sin(t)*(exp(cos(t))-2*cos(4*t)-sin(t/12)^5)\n y=cos(t)*(exp(cos(t))-2*cos(4*t)-sin(t/12)^5)")

> print(p)

 

(三)脸谱图

> #脸谱图

> library(aplpack)

> set.seed(100)

> x=apply(matrix(sample(1:1000,128,),16,8), 2, sort)

> faces(x,face.type=2)

> title(main="随机数_faces",

+       col.main='blue',cex.main=1.5,

+       font.main=2,sub = "吉林说R图系列",

+       col.sub =  "gray20")

(四)调和曲线图

> #调和曲线图

> unison=function(x,main,col.main,cex.main,

+                 font.main,sub,col.sub){

+   if(is.data.frame(x)==T)

+     x=as.matrix(x)

+   t=seq(-pi,pi,pi/30)

+   m=nrow(x)

+   n=col(x)

+   f=array(0,c(m,length(t)))

+   for( i in 1:m){

+     f[i,]=x[i,1]/sqrt(2)

+     for( j in 2:n){

+       if(j%%2==0)

+         f[i,]=f[i,]+x[i,j]*sin(j/2*t)

+       else

+         f[i,]=f[i,]+x[i,j]*cos(j%%2*t)

+     }

+   }

+   plot(c(-pi,pi),c(min(f),max(f)),type="n",

+        main=main,col.main=col.main,font.main=font.main,

+        cex.main=cex.main,sub=sub,col.sub=col.sub,xlab="t",

+        ylab="f(t)")

+   for(i in 1:m)

+     lines(t,f[i,],col=i)

+ }

> set.seed(100)

> x=data.frame(yuwen=abs(runif(5,60,100)),

+              shuxue=abs(runif(5,60,100)),

+              wuli=abs(runif(5,60,100)),

+              huaxue=abs(runif(5,60,100)),

+              zhengzhi=abs(runif(5,60,100)))

> unison(x,main="学生成绩调和曲线_unison",

+        col.main='blue',cex.main=1.5,

+        font.main=2,sub = "吉林说R图系列",

+        col.sub =  "gray20")

 

(五)星相图

> #星相图

> stars(mtcars[, 1:7],draw.segments = T, key.loc = c(14, 2), full = FALSE)

> title(main="汽车_stars",

+       col.main='blue',cex.main=1.5,

+       font.main=2,sub = "吉林说R图系列",col.sub =  "gray20")


(六)雷达图

> #雷达图

> stars(mtcars[, 1:7], locations = c(0, 0), radius = FALSE,

+       key.loc = c(0, 0),lty = 2,  col.lines = rainbow(100))

> title(main="汽车_stars",

+       col.main='blue',cex.main=1.5,

+       font.main=2,sub = "吉林说R图系列",col.sub =  "gray20")

 

(七)聚类图

> #聚类图

> #### train word2vec

> #install.packages("devtools")

> library(devtools)

> #install_github("bmschmidt/wordVectors")

> library(wordVectors)

> model = train_word2vec("yitian_split.txt", output="yitian_split.bin",

+  threads = 2, vectors = 100, window=12, force = T)

> vec = read.vectors("yitian_split.bin")

> rr = sapply(rolesl, function(x) x[1])

> cos_dist = cosineDist(vec[rr,],vec[rr,])

> hc = hclust(as.dist(cos_dist), method = "average")

> plot(hc,main=NULL,sub=NULL,axes = F,ann = F)

> title(main="聚类图_hclust ",

+       col.main='blue',cex.main=1.5,

+       font.main=2,sub = "吉林说R图系列",

+       col.sub =  "gray20")


(八)树图

>#树图

> install.packages("rpart")

> install.packages("rpart.plot")

> library(rpart)

> library(rpart.plot)

> multi.class.model <- rpart(Reliability ~ ., data=cu.summary)

> rpart.plot(multi.class.model,

+            main="vehicle reliability-rpart\n(multi class response)",

+            col.main='blue',cex.main=1.5,

+            sub = "吉林说R图系列",

+            col.sub =  "gray20")

(九)社交网络图

> #社交网络图

> library(igraph)

> rm(list=ls())

> data=read.csv("app.csv",header= T,stringsAsFactors = F)

> #head(data)

> #dim(data)

> g2= graph.data.frame(d = data,directed = F)

> com = walktrap.community(g2, steps = 10)

> V(g2)$sg=com$membership

> V(g2)$color = rainbow(6,alpha=0.1)[V(g2)$sg]

> E(g2)$color=V(g2)[name=ends(g2,E(g2))[,2]]$color

> #igraph_options()

> V(g2)$label=NA  

> V(g2)[degree(g2)>=30]$label=V(g2)[degree(g2)>=30]$name

> dev.off()

> x<-par(bg="white")

> plot(g2,layout=layout.kamada.kawai, vertex.size=0,

+      vertex.color= "red2", edge.width=0.5,

+      edge.color = E(g2)$color,vertex.frame.color=NA,

+      margin= rep(0, 4),vertex.label=V(g2)$label,

+      vertex.label.color='black',

+      vertex.label.font=2,axes = T)

> title(main="APP使用情况社交网络图",

+       col.main='blue',cex.main=1.5,

+       font.main=2,sub = "吉林说R图系列",

+       col.sub =  "gray20")


(十)词云图

> #分词云图

library(showtext)

library(ggplot2)

rm(list=ls())

### read data

xizongjianghua = readLines("习近平总书记在庆祝中国共产党成立95周年纪念大会上的讲话.Txt")

xizongjianghua[1:10]

length(xizongjianghua)

head(xizongjianghua)

#### cut paragraph

zishu=nchar(xizongjianghua)

zishu1=data.frame(zishu,duanluo=1:154)

plot(zishu)

#[[:lower:]] 小写字母

#[[:upper:]] 大写字母

#[[:alpha:]] 所以字母 ([[:lower:]] and [[:upper:]])

#[[:digit:]] 数字: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9

##[[:alnum:]] 字母和数字 ([[:alpha:]] and [[:digit:]])

#[[:blank:]] 空白字符: space and tab

#[[:cntrl:]] 控制字符

#[[:punct:]] 标点符号: ! ” # % & ' ( ) * + , - . / : ;

#[[:space:]] 空格字符:制表符,换行符, 垂直制表符,换页符,回车和空格

#[[:xdigit:]] 十六进制数字: 0-9 A B C D E F a b c d e f

#[[:print:]]控制字符 ([[:alpha:]], [[:punct:]] and space)

#[[:graph:]] 图形化字符 ([[:alpha:]] and [[:punct:]])

xizongjianghua1 <- gsub("[0-90123456789 < > ~]","",xizongjianghua)  

xizongjianghua1 <- gsub("[[:digit:]]*", "", xizongjianghua1)

xizongjianghua1 <- gsub("[a-zA-Z]", "", xizongjianghua1)   

#清除英文字符  

xizongjianghua1 <- gsub("\\.", "", xizongjianghua1)     

 #清除全英文的dot符号

xizongjianghua1 <- gsub("[[:punct:]]", "", xizongjianghua1)      

#清除全英文的dot符号

xizongjianghua1 <- gsub("[[:blank:]]", "", xizongjianghua1)      

#清除全英文的dot符号

#### split words

library(jiebaR)

cutter = worker(bylines = TRUE, stop_word ="stopword.txt")

#new_user_word(cutter, unlist(rolesl), rep("n", length(unlist(rolesl))))  

# 插入新词

xizongjianghua_words = cutter[xizongjianghua1]

xizongjianghua_split = sapply(xizongjianghua_words, paste, collapse = " ")

writeLines(xizongjianghua_split, "xizongjianghua_split.txt")

library(wordcloud)

library(SnowballC)

v=table(unlist(xizongjianghua_words ))

v=sort(v,deceasing=T)

d=data.frame(v)

word=d$Var1

freq=d$Freq

d=data.frame(word,freq)

par(bg="lightyellow")

library(Rcpp)

library(RColorBrewer)

library(wordcloud)

#grayLevels<-gray((d$freq)/(max(d$freq)+140))

#wordcloud(d$word,d$freq,colors=grayLevels)

rainbowLevels<-rainbow((d$freq)/(max(d$freq)-10))

wordcloud(d$word,d$freq,min.freq=3,,random.order=F, scale = c(4.5, .5),col=rainbow(100))

title(main="学习《习近平总书记在庆祝中国共产党\n成立95周年纪念大会上的讲话》_wordcloud",

      col.main='blue',cex.main=1.5,

      font.main=2,sub = "吉林说R图系列",

      col.sub =  "gray20")

 

四、结语

至此,已基本将我所熟知的图形及实现代码进行了简单的展示,当然由于本人能力有限及审美问题,图形还有很大的改进空间,大家可以根据自己的需求和爱好选择性的尝试,掌握绘图的基本要领。由于这里只是以兴趣爱好的形式进行排版,内容难免冗赘拖沓,也请各位批评指正,积极反馈给本人(微信:18566011370),在下一次系列文章中作进一步改进。

五、致谢

感谢刘珍珍同学对我学习的督导,感谢黎秀慧及何翠同学对我工作的支持,因为有你们的帮助,我才能顺利的完成本文的撰写,因为有你们的支持,生活工作变得非常之美好。


(小编提示,如果觉得很赞,就支持一下作者吧!!!)


【温馨提示】本文所有数据、word,请点击“阅读原文”,直接进入云盘下载哦!  访问密码 88f2


您可能也对以下帖子感兴趣

文章有问题?点此查看未经处理的缓存