본문 바로가기
Project

[R stdio] Word Cloud(워드 클라우드) 만들기 - 1

by 배애앰이 좋아 2020. 5. 25.
반응형

데이터 시각화를 위한 world cloud

 

기본적으로 word cloud를 만들기 위해서는 "worldcloud"라는 패키지가 필요합니다.

그 후 word와 각 word에 해당되는 상대값을 넣어주고 실행시키게 되면

300으로 상대적인 값이 제일 큰 Seoul 이 크게 표시가 되고 그 후 200 값인 Busan 50 값인 jeju가 제일 적게 표시가 됩니다.

 

이렇게 Tag Cloud (태그 클라우드) 또는 World Cloud (워드 클라우드)는 메타 데이터에서 얻어진 태그들을 분석하여 중요도나 인기도 등을 고려하여 시각적으로 늘어 놓은 이미지를 이야기합니다.

 

> install.packages("wordcloud")
> library(wordcloud)
> word<-c("Seoul", "Busan", "Jeju")
> freq<-c(300,200,50)
> wordcloud(word, freq)
>wordcloud(word,freq, colors=rainbow(7))
> wordcloud(word,freq, random.order = T,colors=rainbow(7))

 

아래는 직접 값을 넣는 것이 아닌 엑셀로 미리 정리해놓은 값들을 불러와서 표시한 world cloud

코로나19에 대해 전세계에서 어디에 감염자가 많은지 표시해주는 world cloud입니다.

 

> co_w<-read.csv("c:/corona19.csv")
> str(co_w)
> wordcloud(co_w$Locations, co_w$cases, colors=rainbow(7))
> wordcloud(co_w$Locations, co_w$cases, min.freq = 10000,random.color = T, colors = rainbow(7))
> wordcloud(co_w$Locations, co_w$cases, min.freq = 10000,random.order = F,random.color = T, colors = rainbow(7))

우리 나라에서의 코로나 감염자 분포 지역 표시

 

> co_d<-read.csv("C:/corona19_D.csv")
> str(co_d)
> wordcloud(co_d$Locations, co_d$cases, min.freq = 10000,random.order = T,random.color = T, colors = rainbow(7))

 

 

아래는 world cloud를 만들기 위해 필요한 패키지들

 

 

아래는 위에서 공부한 것을 적용시켜서 만들어본 world cloud로 4차 산업에서 과연 어떤 키워드들이 인기 있을 까 궁금하여 만들어보았습니다. 아래는 작성 코드입니다.

 

> library(wordcloud)
> library(XML)
> library(httr)
> library(tm)

> web<-GET('https://news.search.yahoo.com/search;_ylt=AwrXgSO3xctejiQA2x_QtDMD;_ylc=X1MDNTM3MjAyNzIEX3IDMgRmcgN1aDNfbmV3c192ZXJ0X2dzBGZyMgNzYi10b3AEZ3ByaWQDSWlvdVo2NnRSd2k0bmw2aVBFYWhSQQRuX3JzbHQDMARuX3N1Z2cDMTAEb3JpZ2luA25ld3Muc2VhcmNoLnlhaG9vLmNvbQRwb3MDNARwcXN0cgMEcHFzdHJsAzAEcXN0cmwDMTIEcXVlcnkDaW5kdXN0cnklMjA0LjAEdF9zdG1wAzE1OTA0MTMyODI-?p=industry+4.0&fr2=sb-top&fr=uh3_news_vert_gs')
> web

Response [https://news.search.yahoo.com/search?p=industry+4.0&fr2=sb-top&fr=uh3_news_vert_gs]
  Date: 2020-05-25 13:31
  Status: 200
  Content-Type: text/html; charset=UTF-8
  Size: 140 kB
<!doctype html><html id="Stencil" class="NoJ...
<!-- fe26.vertical.search.gq1.yahoo.com Mon ...

> doc<-htmlParse(web)
> news<-xpathSApply(doc, "//div[@id='results']//a", xmlValue)
> news

 [1] "Ad"                                                                                                                                                                   
 [2] "Advanced Engineering Industry - Advanced Manufacturing"                                                                                                               
 [3] "www.great.gov.uk"                                                                                                                                                     
 [4] "The UK Has Seen Rapid Growth In Supply Chain Industries - Find Out More Today. A Thriving Manufacturing Industry Makes The UK A Great Place To Invest - Find Out How."
 [5] "Contact Us"                                                                                                                                                           
 [6] "Invest In The UK"                                                                                                                                                     
 [7] "Advanced Manufacturing"                                                                                                                                               
 [8] "Setup In The UK"                                                                                                                                                      
 [9] "Setup Guides"                                                                                                                                                         
[10] "Invest In GREAT"                                                                                                                                                      
[11] ""                                                                                                                                                                     
[12] "Microsoft (MSFT) to Buy Metaswitch, Steps Up Edge Computing"                                                                                                          
[13] ""                                                                                                                                                                     
[14] "2 “Strong Buy” 5G Stocks to Snap Up (And 1 to Avoid)"                                                                                                               
[15] "Edited Transcript of ED4.DE earnings conference call or presentation 7-May-20 8:30am GMT"                                                                             
[16] ""                                                                                                                                                                     
[17] "3D Printing Going Mainstream and This ETF Could go Along for the Ride"                                                                                                
[18] ""                                                                                                                                                                     
[19] "5 Must-Buy Electronics Stocks to Beat Coronavirus Woes"                                                                                                               
[20] ""                                                                                                                                                                     
[21] "Why women's voices are missing from the future of work debate"                                                                                                        
[22] ""                                                                                                                                                                     
[23] "Nokia to Help PGE Systemy Digitize Electrical Grid in Poland"                                                                                                         
[24] "Edited Transcript of WSU.DE earnings release 18-Mar-20 7:30am GMT"                                                                                                    
[25] ""                                                                                                                                                                     
[26] "InterDigital & Anritsu Team Up for 5G-Backed Experiments"                                                                                                             
[27] ""                                                                                                                                                                     
[28] "4 Electronic Stocks Worth a Bet Despite the Coronavirus Jolt"                                                                                                         
[29] "Ad"                                                                                                                                                                   
[30] "Advanced Engineering Industry - Advanced Manufacturing"                                                                                                               
[31] "www.great.gov.uk"                                                                                                                                                     
[32] "The UK Has Seen Rapid Growth In Supply Chain Industries - Find Out More Today. A Thriving Manufacturing Industry Makes The UK A Great Place To Invest - Find Out How."
[33] "Contact Us"                                                                                                                                                           
[34] "Invest In The UK"                                                                                                                                                     
[35] "Advanced Manufacturing"                                                                                                                                               
[36] "Setup In The UK"                                                                                                                                                      
[37] "Setup Guides"                                                                                                                                                         
[38] "Invest In GREAT"                                                                                                                                                      
[39] "2"                                                                                                                                                                    
[40] "3"                                                                                                                                                                    
[41] "Next"                                                                                                                                                                 
[42] "00:15"                                                                                                                                                                
[43] "A CIO's Guide to Industry 4.0 - Infiniti's Latest Article Reveals the Key Steps for Developing the Right Digital Capabilities"                                        
[44] "00:45"                                                                                                                                                                
[45] "AI robot Sophia visits Vietnam, talks about robotics"

> corpus<-Corpus(VectorSource(news))
> inspect(corpus) //결과 보여줌
> news
> corpus<-tm_map(corpus, tolower) //소문자로 바꿔줌
> corpus<-tm_map(corpus,removeWords, stopwords("english")) 
> corpus<-tm_map(corpus,removeNumbers)
> corpus<-tm_map(corpus, removeFunctuation)
> corpus<-tm_map(corpus, stemDocument, language="english")
> corpus<-tm_map(corpus, stripWhitespace)

 

위의 궁금증을 해결하기 위해 필요한 데이터를 모으기 위해서 아래 사이트를 참고하였는데 해당 사이트는 4차 산업을 야후에서 친 페이지로 뉴스 목록으로 들어가서 뉴스들의 제목을 크롤링해왔습니다. 그리고 가져온 뉴스 제목들을 가져와서 키워드 분석하였습니다.

 

https://news.search.yahoo.com/search;_ylt=AwrXgSO3xctejiQA2x_QtDMD;_ylc=X1MDNTM3MjAyNzIEX3IDMgRmcgN1aDNfbmV3c192ZXJ0X2dzBGZyMgNzYi10b3AEZ3ByaWQDSWlvdVo2NnRSd2k0bmw2aVBFYWhSQQRuX3JzbHQDMARuX3N1Z2cDMTAEb3JpZ2luA25ld3Muc2VhcmNoLnlhaG9vLmNvbQRwb3MDNARwcXN0cgMEcHFzdHJsAzAEcXN0cmwDMTIEcXVlcnkDaW5kdXN0cnklMjA0LjAEdF9zdG1wAzE1OTA0MTMyODI-?p=industry+4.0&fr2=sb-top&fr=uh3_news_vert_gs

 

industry 4.0 - Yahoo Search Results

Thomson Reuters StreetEvents via Yahoo Finance· 3 days agoDigitalization is a driver of profitability and efficiency, especially in the combination with worldwide service excellence measures, but as well as internally in the plant known as

news.search.yahoo.com

 

아래는 상세 코드 및 설명입니다. 

 

> ktm<-DocumentTermMatrix(corpus)
> inspect(ktm)

> findFreqTerms(ktm, 3) //3개 이상인 거 표시

> corpus<-tm_map(corpus,removeWords, c("invest", "stock")) // 해당 키워드 배제하기

 

ktm은 원래 리스트인데 아래 코드를 통해 matrix으로 바꿈.

 

w<-as.matrix(ktm)

 

최종 결과 :

 

> wordcloud(words = names(wordFreq), freq = wordFreq, random.color = T, colors = rainbow(7))

최종 결과를 보며 생각보다 결과가 잘 나오지 않는 것을 알 수 있었습니다. 

이렇게 결과가 별로 안 나온 이유는 활용한 기본 데이터 부족 및 좋은 데이터가 아니라고 생각하였습니다.

그래서 다시 다른 데이터를 이용하여 다른 주제로 해볼까 합니다. 

선택한 새로운 주제 => 영화 별 감상 키워드 world cloud를 만들어 볼 생각입니다.

반응형

댓글