ABOUT ME

코딩 테스트 풀어보는 블로그

Today
Yesterday
Total
  • 코로나19 한국 현황 차트로 그려보기
    카테고리 없음 2020. 4. 15. 18:10
    728x90

    코로나19 한국 현황 차트로 그려보기

    ‘Do it! 쉽게 배우는 R 데이터 분석’
    http://www.yes24.com/Product/Goods/44015086
    책에서 배운내용을 토대로, 코로나19 한국 현황을 차트로 그려보겠습니다.

    필요한 패키지를 설치

    필요한 패키지를 설치하는 코드 입니다. 한번만 실행해서, 설치한 뒤에는
    다시 설치하지 않아도 됩니다. 코드에는 ‘#’ 주석으로 막아 두었습니다.
    설치하실 때는 #을 지우고 설치하세요.

    • 'remotes’는 github에서 패키지를 다운로드 받아서, 설치할 수 있도록 도와주는 패키지 입니다.

    • 'youngwoos/corona19’ 패키지가 우리가 공부하고 있는 책의 저자이기도 하신, 김영우님이 만드신 패키지이구요, corona19 한국 현황을 data
      frame으로 받아 옮니다.

    • '코로나19 데이터셋은' https://github.com/jihoo-kim/Coronavirus-Dataset 여기서 받아 옮니다

    필요한 라이브러리 로드

    https://github.com/youngwoos/corona19 에 있는 샘플 차트+

    state <- getdata("time")
    state
    ## # A tibble: 85 x 7
    ##    date        time   test negative confirmed released deceased
    ##    <date>     <int>  <int>    <int>     <int>    <int>    <int>
    ##  1 2020-04-13     0 518743   494815     10537     7447      217
    ##  2 2020-04-12     0 514621   490321     10512     7368      214
    ##  3 2020-04-11     0 510479   485929     10480     7243      211
    ##  4 2020-04-10     0 503051   477303     10450     7117      208
    ##  5 2020-04-09     0 494711   468779     10423     6973      204
    ##  6 2020-04-08     0 486003   457761     10384     6776      200
    ##  7 2020-04-07     0 477304   446323     10331     6694      192
    ##  8 2020-04-06     0 466804   437225     10284     6598      186
    ##  9 2020-04-05     0 461233   431425     10237     6463      183
    ## 10 2020-04-04     0 455032   424732     10156     6325      177
    ## # ... with 75 more rows
    ggplot(data = state, aes(x = date, y = confirmed)) + 
      geom_area(color="darkorange", fill="orange") + 
      scale_x_date(date_breaks = "weeks" , date_labels = "%m-%d")

    코로나19 차트를 그리기에 앞서서, 좋은 차트 참고해 보기

    어떤 분이 만드신 코로나19 차트입니다. 제가 보기에는, 많은 정보를 잘
    보여주는 잘 만들어진 차트입니다.
    http://www.ddanzi.com/index.php?mid=free&statusList=HOT%2CHOTBEST%2CHOTAC%2CHOTBESTAC&document_srl=603724861

    3개의 차트가 있구요, 첫번째 차트는 확진자수를 누적/일별로 듀얼 엑시스로
    차트를 표현해서, 누적수화 일별 증가 추세를 잘 알아 볼 수 있는
    차트입니다.

    나머지 2번째 3번째 차트는, 확진자수의 일별 변화량의 선행지표로 사용될 수
    있는, 검사결과 확진율과, 일별 검사 건수 입니다.

    첫번째 차트는 다음챕터에서 함께 그려보겠구요, 2번째, 3번째 차트는
    직접한번 그려보시기를 추천드립니다.

    차트 그리기 전에 데이터 정리 부터 할께요

    # x date: 일자=
    # y confirmed: 누적 양성 결과 수 (확진)
    
    # 차트를 그리기 위해서는 confirmed로 부터 일별 양성 결과수를 알아내야 합니다.
    
    # 우선은 날짜별로 오름차순으로 정렬하구요.
    state = state[order(as.Date(state$date, format="%Y-%m-%d")),]
    # y new_confirmed: 일별 양성 결과 수 (확진)
    
    # ave() 에서 모든 row를 한 그룹으로 묶기 위해서, 모든 row의 id 에 0을 저장합니다.
    state$id = 0
    
    # ave()와 diff()를 활용해서, 일별 양성 결과수(new_confirmed)를 알아냅니다.
    state$new_confirmed <- ave(state$confirmed, state$id, FUN = function(x) c(0, diff(x)))
    
    state
    ## # A tibble: 85 x 9
    ##    date        time  test negative confirmed released deceased    id
    ##    <date>     <int> <int>    <int>     <int>    <int>    <int> <dbl>
    ##  1 2020-01-20    16     1        0         1        0        0     0
    ##  2 2020-01-21    16     1        0         1        0        0     0
    ##  3 2020-01-22    16     4        3         1        0        0     0
    ##  4 2020-01-23    16    22       21         1        0        0     0
    ##  5 2020-01-24    16    27       25         2        0        0     0
    ##  6 2020-01-25    16    27       25         2        0        0     0
    ##  7 2020-01-26    16    51       47         3        0        0     0
    ##  8 2020-01-27    16    61       56         4        0        0     0
    ##  9 2020-01-28    16   116       97         4        0        0     0
    ## 10 2020-01-29    16   187      155         4        0        0     0
    ## # ... with 75 more rows, and 1 more variable: new_confirmed <dbl>

    코로나19 확진자수(누적,일별) 차트그리기 시작

    # 가장 기본적인 그래프입니다. 시간에 따라서, 누적 양성 결과수가 얼마나 증가하는지 그래프로 그려 봤습니다.
    
    # todo : 일별 신규 양성 결과수를 바차트로 추가해 보겠습니다.
    ggplot(data = state, aes(x = date)) +
      geom_line(aes(y = confirmed))

    # x date: 일자
    # gome_line() y confirmed: 누적 양성 결과 수 (확진)
    # geom_bar() y new_confirmed: 신규 양성 결과 수 (확진)
    
    # 누적 양성 결과와 함께, 일별 신규로 양성 결과수를 바차트로 추가했습니다.
    
    # todo : 바차트가 라인차트에 비해서 낮아서, 보기가 불편합니다.
    ggplot(data = state, aes(x = date)) +
      geom_line(aes(y = confirmed)) +
      geom_bar(aes(y = new_confirmed), stat = "identity")

    # x date: 일자
    # gome_line() y confirmed: 누적 양성 결과 수 (확진)
    # geom_bar() y new_confirmed: 신규 양성 결과 수 (확진)
    
    # 바차트가 오른쪽에 별도의 y-axis를 사용하기 위해서,
    # aes가 inherit되는 것을 false로 합니다.
    # 즉 앞에서 그려진 geom_line의 aes와는 다른 aes로 바차트를 그리겠다, 라고 코딩해놓는 것입니다.
    # 아직 바차트에는 변화는 없습니다.
    ggplot(data = state, aes(x = date)) +
      geom_line(aes(y = confirmed)) +
      geom_bar(aes(x = date, y = new_confirmed), stat = "identity", inherit.aes = FALSE)

    # x date: 일자
    # gome_line() y confirmed: 누적 양성 결과 수 (확진)
    # geom_bar() y new_confirmed: 신규 양성 결과 수 (확진)
    
    # 라인 차트보다 바차트가 위에 있어서, 보기 안좋습니다.
    # todo : 라인 차트가 바차트 위에 있게 합니다.
    ggplot(data = state, aes(x = date)) +
      geom_line(aes(y = confirmed)) +
      geom_bar(aes(x = date, y = new_confirmed*7), stat = "identity", inherit.aes = FALSE) +
      scale_y_continuous(sec.axis = sec_axis(~./7, name = "new_confirmed"))

    # x date: 일자
    # gome_line() y confirmed: 누적 양성 결과 수 (확진)
    # geom_bar() y new_confirmed: 신규 양성 결과 수 (확진)
    
    # 라인차트가 바차트 위로 올라오면서, 앞에 차트보다 보기 편해졌습니다.
    # todo : 좌우 양쪽에 있는 y-axis의 label이 보기 안좋네요.
    ggplot(data = state, aes(x = date)) +
      geom_bar(aes(x = date, y = new_confirmed*7), stat = "identity", inherit.aes = FALSE) +
      scale_y_continuous(sec.axis = sec_axis(~./7, name = "new_confirmed")) +
      geom_line(aes(y = confirmed))

    # x date: 일자
    # gome_line() y confirmed: 누적 양성 결과 수 (확진)
    # geom_bar() y new_confirmed: 신규 양성 결과 수 (확진)
    
    # 좌우 양쪽에 있는 y-axis의 label을 올바른 레이블로 변경했습니다.
    # todo : 2월 15일 이전 수치는 너무 낮아서 크게 필요 없을 것 같습니다.
    
    y_label = '누적 확진자'
    
    ggplot(data = state, aes(x = date)) +
      geom_bar(aes(x = date, y = new_confirmed*7), stat = "identity", inherit.aes = FALSE) +
      ylab(y_label) +
      scale_y_continuous(sec.axis = sec_axis(~./7, name = "일별 신규 확진자")) +
      geom_line(aes(y = confirmed))

    # x date: 일자
    # gome_line() y confirmed: 누적 양성 결과 수 (확진)
    # geom_bar() y new_confirmed: 신규 양성 결과 수 (확진)
    
    # 오늘부터 20일전 데이터만 그렸습니다.
    # todo : 색이 없어서, 보기 안좋네요, 색을 넣겠습니다.
    
    y_label = '누적 확진자'
    
    ggplot(data = state, aes(x = date)) +
      geom_bar(aes(x = date, y = new_confirmed*7), stat = "identity", inherit.aes = FALSE) +
      ylab(y_label) +
      scale_y_continuous(sec.axis = sec_axis(~./7, name = "일별 신규 확진자")) +
      geom_line(aes(y = confirmed)) + 
      scale_x_date(limits = c(Sys.Date() - 20, NA))
    ## Warning: Removed 66 rows containing missing values (position_stack).
    
    ## Warning: Removed 1 rows containing missing values (geom_bar).
    
    ## Warning: Removed 66 row(s) containing missing values (geom_path).

    # x date: 일자
    # gome_line() y confirmed: 누적 양성 결과 수 (확진)
    # geom_bar() y new_confirmed: 신규 양성 결과 수 (확진)
    
    # 색이 없어서, 보기 안좋네요, 색을 넣겠습니다.
    # 누적 확진자는 red, 일별 신규 확진자는 orange
    # line 굵기 1.5
    # todo : 그래프가 너무 작네요, 그래프 크기를 키워 보겠습니다.
    
    y_label = '누적 확진자'
    
    ggplot(data = state, aes(x = date)) +
      geom_bar(aes(x = date, y = new_confirmed*7), stat = "identity", inherit.aes = FALSE, color = 'orange', fill = 'orange') +
      ylab(y_label) +
      scale_y_continuous(sec.axis = sec_axis(~./7, name = "일별 신규 확진자")) +
      geom_line(aes(y = confirmed, color = 'red'), lwd = 1.5) + 
      scale_x_date(limits = c(Sys.Date() - 20, NA))
    ## Warning: Removed 66 rows containing missing values (position_stack).
    
    ## Warning: Removed 1 rows containing missing values (geom_bar).
    
    ## Warning: Removed 66 row(s) containing missing values (geom_path).

    # x date: 일자
    # gome_line() y confirmed: 누적 양성 결과 수 (확진)
    # geom_bar() y new_confirmed: 신규 양성 결과 수 (확진)
    
    # fig.width/height를 키워서, 그래프 크기를 키웠습니다.
    # todo : 키워놓고 보니, grid가 너무 큰 단위로 그려저 있네요. 보다 작은 단위도 표시하겠습니다.
    
    y_label = '누적 확진자'
    
    ggplot(data = state, aes(x = date)) +
      geom_bar(aes(x = date, y = new_confirmed*7), stat = "identity", inherit.aes = FALSE, color = 'orange', fill = 'orange') +
      ylab(y_label) +
      scale_y_continuous(sec.axis = sec_axis(~./7, name = "일별 신규 확진자")) +
      geom_line(aes(y = confirmed, color = 'red'), lwd = 1.5) + 
      scale_x_date(limits = c(Sys.Date() - 20, NA))

    # x date: 일자
    # gome_line() y confirmed: 누적 양성 결과 수 (확진)
    # geom_bar() y new_confirmed: 신규 양성 결과 수 (확진)
    
    # x-axis의 날짜를 일단위로 표시되도록 변경했습니다.
    # todo : y-axis도 보다 작은 단위로 표시되도록 수정하겠습니다.
    
    y_label = '누적 확진자'
    
    datebreaks <- seq(Sys.Date() - 20, Sys.Date(), by="1 day")
    
    ggplot(data = state, aes(x = date)) +
      geom_bar(aes(x = date, y = new_confirmed*7), stat = "identity", inherit.aes = FALSE, color = 'orange', fill = 'orange') +
      ylab(y_label) +
      scale_y_continuous(sec.axis = sec_axis(~./7, name = "일별 신규 확진자")) +
      geom_line(aes(y = confirmed, color = 'red'), lwd = 1.5) + 
      scale_x_date(breaks = datebreaks, limits = c(Sys.Date() - 20, NA), date_labels = "%m-%d")

    # x date: 일자
    # gome_line() y confirmed: 누적 양성 결과 수 (확진)
    # geom_bar() y new_confirmed: 신규 양성 결과 수 (확진)
    
    # y-axis도 보다 작은 단위로 표시되도록 수정했습니다.
    # todo : 'red'라는 필요없는 regend가 표시 되고 있네요, 차트에서 지우겠습니다.
    
    y_label = '누적 확진자'
    
    datebreaks <- seq(Sys.Date() - 20, Sys.Date(), by="1 day")
    ybreaks <- seq(0, 10000, 500)
    
    ggplot(data = state, aes(x = date)) +
      geom_bar(aes(x = date, y = new_confirmed*7), stat = "identity", inherit.aes = FALSE, color = 'orange', fill = 'orange') +
      ylab(y_label) +
      scale_y_continuous(sec.axis = sec_axis(~./7, name = "일별 신규 확진자"), breaks = ybreaks) +
      geom_line(aes(y = confirmed, color = 'red'), lwd = 1.5) + 
      scale_x_date(breaks = datebreaks, limits = c(Sys.Date() - 20, NA), date_labels = "%m-%d")

    # x date: 일자
    # gome_line() y confirmed: 누적 양성 결과 수 (확진)
    # geom_bar() y new_confirmed: 신규 양성 결과 수 (확진)
    
    # 'red'라는 필요없는 regend가 표시 되고 있네요, 차트에서 지우겠습니다.
    # todo : 오늘 부터 20일 이전 데이터만 표시 하고 있었네요, 30일 이전 데이터 부터 표시되도록 변경합니다.
    
    y_label = '누적 확진자'
    
    datebreaks <- seq(Sys.Date() - 20, Sys.Date(), by="1 day")
    ybreaks <- seq(0, 10000, 500)
    
    ggplot(data = state, aes(x = date)) +
      geom_bar(aes(x = date, y = new_confirmed*7), stat = "identity", inherit.aes = FALSE, color = 'orange', fill = 'orange') +
      ylab(y_label) +
      scale_y_continuous(sec.axis = sec_axis(~./7, name = "일별 신규 확진자"), breaks = ybreaks) +
      geom_line(aes(y = confirmed, color = 'red'), lwd = 1.5, show.legend = FALSE) + 
      scale_x_date(breaks = datebreaks, limits = c(Sys.Date() - 20, NA), date_labels = "%m-%d")

    # x date: 일자
    # gome_line() y confirmed: 누적 양성 결과 수 (확진)
    # geom_bar() y new_confirmed: 신규 양성 결과 수 (확진)
    
    # 오늘 부터 20일 이전 데이터만 표시 하고 있었네요, 30일 이전 데이터 부터 표시되도록 변경했습니다.
    
    # 다 그렸습니다. ^^ 수고하셨습니다.
    # 아래는 추가로 trend line을 그려볼께요.
    
    y_label = '누적 확진자'
    
    sinceWhen = 30
    datebreaks <- seq(Sys.Date() - sinceWhen, Sys.Date(), by="1 day")
    ybreaks <- seq(0, 10000, 500)
    
    ggplot(data = state, aes(x = date)) +
      geom_bar(aes(x = date, y = new_confirmed*7), stat = "identity", inherit.aes = FALSE, color = 'orange', fill = 'orange') +
      ylab(y_label) +
      scale_y_continuous(sec.axis = sec_axis(~./7, name = "일별 신규 확진자"), breaks = ybreaks) +
      geom_line(aes(y = confirmed, color = 'red'), lwd = 1.5, show.legend = FALSE) + 
      scale_x_date(breaks = datebreaks, limits = c(Sys.Date() - sinceWhen, NA), date_labels = "%m-%d")

    # x date: 일자
    # gome_line() y confirmed: 누적 양성 결과 수 (확진)
    # geom_bar() y new_confirmed: 신규 양성 결과 수 (확진)
    
    # geom_smooth()를 사용해서, 일별 양성 확진자수의 증감을 trend-line으로 그려 보았습니다.
    
    y_label = '누적 확진자'
    
    sinceWhen = 50
    datebreaks <- seq(Sys.Date() - sinceWhen, Sys.Date(), by="1 day")
    ybreaks <- seq(0, 10000, 500)
    
    ggplot(data = state, aes(x = date)) +
      geom_bar(aes(x = date, y = new_confirmed*7), stat = "identity", inherit.aes = FALSE, color = 'orange', fill = 'orange') +
      ylab(y_label) +
      scale_y_continuous(sec.axis = sec_axis(~./7, name = "일별 신규 확진자"), breaks = ybreaks) +
      geom_line(aes(y = confirmed, color = 'red'), lwd = 1.5, show.legend = FALSE) + 
      scale_x_date(breaks = datebreaks, limits = c(Sys.Date() - sinceWhen, NA), date_labels = "%m-%d") +
      geom_smooth(aes(x = date, y = new_confirmed*7))
    ## `geom_smooth()` using method = 'loess' and formula 'y ~ x'

    #검사결과 확진율 차트

    차트 모양은 아래 링크 참고하세요.
    http://www.ddanzi.com/index.php?mid=free&statusList=HOT%2CHOTBEST%2CHOTAC%2CHOTBESTAC&document_srl=603724861

    마지막으로 함께 R 스터디 하실분 https://skysign.github.io/DAT/ 여기로 오세요

    728x90
Designed by Tistory.