ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [R] Bar Chart Race 재현 03
    Project/Bar Chart Race (with R) 2020. 7. 11. 11:02

    목차

     

    서론

     Bar Chart Race 재현 프로젝트를 수행하면서 전체적인 프로세스를 소개하였고 공공데이터를 수집하는 방법과 Bar Chart Race가 가능하도록 데이터를 가공하는 과정을 소개하였다. 이어서 가공한 데이터를 기반으로 데이터 시각화 하는 방법에 대해 가이드 할 예정이다. R에서는 기본으로 제공하는 graphics라는 라이브러리가 있으나, 시각화를 자유롭게 핸들링하기 위해서는 ggplot2를 추천한다. 본 재현에서는 기존에 있는 graphics 라이브러리가 아닌 ggplot2를 이용하여 시각화를 한다.

     

    <그림 1> Bar Chart Race 재현 프로세스

    데이터 시각화

     reshape2 라이브러리에 있는 melt()를 사용하여 [표 1]과 같이 데이터를 가공하고 이를 바탕으로 그래프를 그리고자 한다. 이때, 기존에 있는 graphics의 barplot() 또는 plot()을 사용하기보다 다양한 파라미터 옵션을 변경하여 자유롭게 핸들링이 가능한 ggplot2 라이브러리를 한다.

     

    region year index rank
    전라남도 1998 1232904 1
    충청남도 1998 906633 2
    전라북도 1998 845769 3
    경상북도 1998 661963 4
    경기도 1998 629632 5

    [표 1] 전처리 한 시도별 쌀 생산량 데이터

     

     

     시도별 미곡생산량(백미) 데이터를 국가통계포탈에서 다운받으면 아래의 crop.csv와 같은 형태로 데이터를 수집할 수 있다. 아래의 스크립트를 거쳐서 [표 1]과 같이 변형한 데이터는 convert_crop이며, 이를 활용하여 시각화 할 수 있다.

    crop.csv
    0.01MB

     

     

    ###local repository setting
    setwd("C:/Users/.../desktop")
    r_data = read.csv("crop.csv", stringsAsFactors = F)
    
    final = data.frame(r_data[,1], stringsAsFactors = F)
    colnames(final) = colnames(r_data)[1]
    for(i in 2:length(r_data))
    {
      if(i%%2==1){
      before = data.frame(r_data[,i], stringsAsFactors = F)
      colnames(before) = colnames(r_data)[i]
      final = cbind(final, before)
      }
    }
    
    r_data = final[-1,]
    
    
    colnames(r_data) = gsub("X", "", colnames(r_data))
    colnames(r_data) = gsub("\\.1", "", colnames(r_data))
    colnames(r_data) = gsub("년", "-", colnames(r_data))
    colnames(r_data) = gsub(".월", "", colnames(r_data))
    colnames(r_data) = gsub("\\..", "-", colnames(r_data))
    colnames(r_data) = gsub("국적별", "country", colnames(r_data))
    r_data$country = gsub(" ", "",r_data$country)
    
    after = data.frame()
    for(i in 1:(length(r_data)/2))
    {
      before = data.frame((2000+i-1), r_data[,(i*2-1):(i*2)], stringsAsFactors = F)
      colnames(before) = c("year", "country", "index")
      after = rbind(after, before)
    }
    
    for(i in 1:length(r_data))
    {
      r_data[,i] = gsub(",", "", r_data[,i])
    }
    
    for(i in 1:length(r_data))
    {
      r_data[,i] = gsub("-", "0", r_data[,i])
    }
    
    for(i in 2:length(r_data))
    {
      r_data[,i] = as.integer(r_data[,i])
    }
    
    for(i in 2:length(r_data))
    {
      r_data[,i] = as.numeric(r_data[,i])
    }
    
    ######reshape2의 melt()활용
    total = melt(r_data)
    colnames(total)  = c("region", "year", "index")

    convert_crop.csv
    0.01MB

     

      매 년마다 1등부터 순서를 만들고, 상위 10 또는 20위까지를 추출하고 ggplot()을 이용해서 시각화를 만들 수 있다. ggplot()을 기준으로 geom_tile, geom_text, scale_y_reverse(), scale_continuous, scale_fill_manual, guide로 구조화할 수 있다.

    total = total %>%
      group_by(year) %>%
      arrange(year, desc(index)) %>%
      mutate(rank = order(index, decreasing = T))
    
    
    data = subset.data.frame(total, rank <= 10, stringAsFactor = F)
    
    p = ggplot(data, aes(y = rank), color = region) +
      geom_tile(aes(x = index/2, height = 0.8, width = index, fill = region),
                alpha = 0.9) +
      # geom_image(aes(x = index, image = paste0("http:",url1)),
      #            hjust = 1,
      #            size = 0.05) +
      geom_text(aes(x = -1, label = paste(region, "  ")),
                vjust = 0.5,
                hjust = 1,
                size = 7,
                fontface='bold',
                family = "jua") +
      geom_text(aes(x = index, label = paste0(" ",format(index,digits = 3)),
                hjust = 0,vjust=0.5),
                size = 9,
                fontface='bold') +
      scale_y_reverse() +
      scale_x_continuous("",labels = scales::comma, expand = c(0.1,0)) +
      scale_fill_manual(values = cols,
                       aesthetics = c("colour", "fill")) +
      guides(color = F)

     

    앞선 과정을 거쳐서 아래와 같은 시각화를 만들 수 있다.

    <그림 2> 시각화 결과

    Lesson Learned

     공공 데이터를 수집해서 시간의 흐름에 따라 어떠한 변화가 있는지 보기 위해 Bar Chart Race를 재현하였다. 수집하는 단계부터 데이터 가공 및 시각화까지 진행했으며, 이를 영상 처리하는 과정까지 진행할 예정이다.

    Reference

    1. 통계청의 국가통계포털(KOSIS), "미곡생산량(백미, 92.9%)", kosis.kr/statHtml/statHtml.do?orgId=101&tblId=DT_1ET0221&conn_path=I2

    2. Hadley Wickham, "reshape2", https://cran.r-project.org/web/packages/reshape2/reshape2.pdf

    3. Worldwide, "graphics", www.rdocumentation.org/packages/graphics

     

     

     

     

     

     

    'Project > Bar Chart Race (with R)' 카테고리의 다른 글

    [R] Bar Chart Race 재현 04  (0) 2020.07.18
    [R] Bar Chart Race 재현 02  (0) 2020.07.05
    [R] Bar Chart Race 재현 01  (0) 2020.05.28

    댓글

Designed by Tistory.