[R] ggwordcloud example

2019. 9. 29. 22:26분석 R/구현

728x90

wordcloud.zip
0.02MB

Library Load

Packages <- c("KoNLP", "dplyr", "ggplot2", "ggwordcloud", "tm")

invisible(lapply(Packages, suppressMessages(library) , character.only = TRUE ))

Data Load

  • data : 가사 모음집
  • stopword : 불용어 리스트
data <- read.table("text_data.txt",
           sep = "\t" , 
           fileEncoding = "utf-8"
           )
stopword <- read.table("stop.txt",
                   sep = "\t" , 
                   fileEncoding = "utf-8")$V1

1차 Data Handling

  • 불용어 처리 및 명사 추출 과정 진행
text = paste(data$V1 , collapse = " " )
text = gsub("\n" , " ", text)
## 1차 stopwords
text2 = removeWords(text , stopword )
## 명사 추출
noun = extractNoun(text2)

2차 Data Handling

  • 명사 빈도수 세기
text <- data.frame(noun) %>% 
  group_by(noun) %>% 
  summarise(n=n()) %>% arrange(desc(n))
text %>% head()
## # A tibble: 6 x 2
##   noun      n
##   <fct> <int>
## 1 너       65
## 2 나       37
## 3 말       26
## 4 사랑     25
## 5 것       23
## 6 오늘     19

3차 Data Handling

  • 아직 처리되지 않은 불용어 추가 처리
## 2차 stopwords
notuse = text$noun %in% c("너","내","나","것" , 
                          "수","한","날" , 
                          "랄라라라랄라라라")
text = text[!notuse,]

text %>% head()
## # A tibble: 6 x 2
##   noun      n
##   <fct> <int>
## 1 말       26
## 2 사랑     25
## 3 오늘     19
## 4 생각     14
## 5 꽃       10
## 6 밤       10

Wordcloud 시각화

ggplot(
  text,
  aes(
    label = noun, size = n,
    color = n ) ) +
  geom_text_wordcloud_area(
    aes(angle = 45 * sample(-2:2, 
                            nrow(text),
                            replace = TRUE,
                            prob = replicate(5,1)
  )),
  area_corr_power = 1.1 ,
  mask = png::readPNG("mike.png"),
  rm_outside = TRUE
  ) +
  scale_size_area(max_size = 11) +
  theme_minimal() +
  scale_color_gradient(low = "red", high = "darkred")

728x90