我创建了一个简单的wordcloud:
require(wordcloud)
words <- c('affectionate', 'ambitious', 'anxious', 'articulate', 'artistic', 'caring', 'contented', 'creative', 'cynical', 'daring', 'dependable', 'easygoing', 'energetic', 'funny', 'generous', 'genuine', 'goodlistener', 'goodtalker', 'happy', 'hardworking', 'humerous', 'impulsive', 'intelligent', 'kind', 'loyal', 'modest', 'optimistic', 'outgoing', 'outrageous', 'passionate', 'perceptive', 'physicallyfit', 'quiet', 'rational', 'respectful', 'romantic', 'shy', 'spiritual', 'spontaneous', 'sweet', 'thoughtful', 'warm')
freqs <- c(134, 53, 0, 5, 0, 247, 0, 78, 0, 0, 134, 178, 79, 344, 63, 65, 257, 0, 109, 113, 0, 0, 107, 51, 199, 24, 67, 232, 0, 109, 24, 28, 29, 2, 105, 70, 0, 35, 64, 156, 66, 45)
wordcloud(words, freqs)
我想将其放入“ grob”中,以便可以使用
grid.arrange()
包中的gridExtra
将其与其他几个图一起排列:require(ggplot2)
p1 <- qplot(1:10, rnorm(10), colour = runif(10))
require(gridExtra)
grid.arrange(p1, my.wordcloud)
我知道我的wordcloud必须做到这一点,但我不知道如何做到这一点。我尝试在
grob()
包中使用gridExtra
函数,但这没有用。有什么建议吗? 最佳答案
适应wordcloud
中的代码以构造需要在grid中填充text.grob的数据应该没有那么困难。在指定限制为0、0和1的窗口后,wordcloud
代码将x,y,text和rot值发送给基本text
函数。
我需要在for循环之前添加它:
textmat <- data.frame(x1=rep(NA, length(words)), y1=NA, words=NA_character_,
rotWord=NA, cexw=NA, stringsAsFactors=FALSE )
在for循环的结尾:
textmat[i, c(1,2,4,5) ] <- c(x1=x1, y1=y1, rotWord=rotWord*90, cexw = size[i] )
textmat[i, 3] <- words[i]
并且需要修改对
.overlap
的调用,因为它显然未导出:if (!use.r.layout)
return(wordcloud:::.overlap(x1, y1, sw1, sh1, boxes))
循环完成后,我无形地返回了它:
return(invisible(textmat[-1, ])) # to get rid of the NA row at the beginning
命名为wordcloud2后:
> tmat <- wordcloud2(c(letters, LETTERS, 0:9), seq(1, 1000, len = 62))
> str(tmat)
'data.frame': 61 obs. of 5 variables:
$ x1 : num 0.493 0.531 0.538 0.487 ...
$ y1 : num 0.497 0.479 0.532 0.475 ...
$ words : chr "b" "O" "M" ...
$ rotWord: num 0 0 0 0 0 0 0 0 0 ...
$ cexw : num 0.561 2.796 2.682 1.421 ...
draw.text <- function(x,y,words,rotW,cexw) {
grid.text(words, x=x,y=y, rot=rotW, gp=gpar( fontsize=9*cexw)) }
for(i in 1:nrow(tmat) ) { draw.text(x=tmat[i,"x1"], y=tmat[i,"y1"],
words=tmat[i,"words"], rot=tmat[i,"rotWord"],
cexw=tmat[i,"cexw"]) }
如建议:
with(tmat, grid.text(x=x1, y=y1, label=words, rot=rotWord,
gp=gpar( fontsize=9*cexw)) } # untested