创建按字母顺序排序的文字云

时间:2016-11-25 13:31:00

标签: r word-cloud

我想为后续数据创建一个词云。

Red     30
Brown   12
Black   16
Green   33
Yellow  18
Grey    19
White   11

我的词云应该是这样的:

enter image description here

按字母顺序对哪些单词进行排序,单词的字体取决于与第二列对应的值。

1 个答案:

答案 0 :(得分:2)

我们可以将每个单词分成字母,然后使用ggplot2::geom_text

为每个字母和图表指定大小
library(ggplot2) # ggplot2_2.2.0

# data
df1 <- read.table(text ="
Red     30
Brown   12
Black   16
Green   33
Yellow  18
Grey    19
White   11", stringsAsFactors = FALSE)

colnames(df1) <- c("col", "size")
# order based on value of size
df1 <- df1[order(df1$col), ]

# separate into letters add size
datPlot <- 
  do.call(rbind,
  lapply(seq(nrow(df1)), function(i){
    myLetter <- c(".", unlist(strsplit(df1$col[i], split = "")))
    data.frame(myLetter = myLetter,
               size = c(10, rep(df1$size[i], length(myLetter) - 1)))
    }))
# each letter gets a sequential number on x axis, y is fixed to 1
datPlot$x <- seq(nrow(datPlot))
datPlot$y <- 1

# plot text
ggplot(datPlot, aes(x, y, label = myLetter, size = size/3)) +
  geom_text(col = "#F89443") +
  scale_size_identity() +
  theme_void()

enter image description here