pl_part2_ch5

ch5. Subplot

df_취업률_500 <- readRDS("df_취업률_500.rds")
df_취업률 <- readRDS( "df_취업률.rds")
df_covid19 <- readRDS("df_covid19.rds")
df_covid19_100 <- readRDS("df_covid19_100.rds")
df_covid19_100_wide <- readRDS("df_covid19_100_wide.rds")
df_covid19_stat <- readRDS("df_covid19_stat.rds")
library(plotly)
Loading required package: ggplot2

Attaching package: 'plotly'
The following object is masked from 'package:ggplot2':

    last_plot
The following object is masked from 'package:stats':

    filter
The following object is masked from 'package:graphics':

    layout
margins_R <- list(t = 50, b = 25, l = 25, r = 25)

기본 구조

## 서브플롯 생성을 위한 기본 Plotly 객체 생성
p_line_wide <- df_covid19_100_wide |> plot_ly()

## 첫 번째 서브플롯 생성
p1 <- p_line_wide |>
  add_trace(type = 'scatter', mode = 'lines', x = ~date,
            y = ~확진자_한국, name = '한국') |>
  layout(title = '한국',
         xaxis = list(tickfont = list(size = 10)),
         yaxis = list(title = list(text = '확진자수')))

## 두 번째 서브플롯 생성
p2 <- p_line_wide |>
  add_trace(type = 'scatter', mode = 'lines', x = ~date,
            y = ~확진자_아시아, name = '아시아') |>
  layout(title = '아시아',
         xaxis = list(tickfont = list(size = 10)),
         yaxis = list(title = list(text = '확진자수')))

## 세 번째 서브플롯 생성
p3 <- p_line_wide |>
  add_trace(type = 'scatter', mode = 'lines', x = ~date,
            y = ~확진자_유럽, name = '유럽') |>
  layout(title = '유럽',
         xaxis = list(tickfont = list(size = 10)),
         yaxis = list(title = list(text = '확진자수')))

## 네 번째 서브플롯 생성
p4 <- p_line_wide |>
  add_trace(type = 'scatter', mode = 'lines', x = ~date,
            y = ~확진자_북미, name = '북미') |>
  layout(title = '북미',
         xaxis = list(tickfont = list(size = 10)),
         yaxis = list(title = list(text = '확진자수')))

## 다섯 번째 서브플롯 생성
p5 <- p_line_wide |>
  add_trace(type = 'scatter', mode = 'lines', x = ~date,
            y = ~확진자_남미, name = '남미') |>
  layout(title = '남미',
         xaxis = list(tickfont = list(size = 10)),
         yaxis = list(title = list(text = '확진자수')))

## 여섯 번째 서브플롯 생성
p6 <- p_line_wide |>
  add_trace(type = 'scatter', mode = 'lines', x = ~date,
            y = ~확진자_아프리카, name = '아프리카') |>
  layout(title = '아프리카',
         xaxis = list(tickfont = list(size = 10)),
         yaxis = list(title = list(text = '확진자수')))

## 일곱 번째 서브플롯 생성
p7 <- p_line_wide |>
  add_trace(type = 'scatter', mode = 'lines', x = ~date,
            y = ~확진자_오세아니아, name = '오세아니아') |>
  layout(title = '오세아니아',
         xaxis = list(tickfont = list(size = 10)),
         yaxis = list(title = list(text = '확진자수')))

## 전체 서브플롯 구성
subplots <- subplot(p1, p2, p3, p4, p5, p6, p7, nrows = 3) |>
  layout(  ## 전체 제목 설정
         title = '최근 100일간 코로나19 확진자수',
         ## 전체 여백 설정
         margin = margins_R) ## margins_R <- list(t = 50, b = 25, l = 25, r = 25),ch2 chunk5

subplots

group_by( )와 do( ) 사용 (서브플롯이 많을 때)

df_covid19_100 |>
  ## 국가명으로 그룹화
  group_by(location) |>
  ## 그룹화한 각각의 데이터 그룹들에 적용할 코드 설정
  do(
    ## 각 그룹화한 데이터를 사용해 Plotly 객체 생성
    p = plot_ly(.) |>
      ## line 모드의 scatter 트레이스 추가
      add_trace(type = 'scatter', mode = 'lines',
                ## X, Y축에 변수 매핑, color를 설정
                x = ~date, y = ~new_cases, name = ~location) |>
      add_annotations(x = 0.5 , y = 1.02, text = ~location,
                      showarrow = F, xref='paper',
                      yref='paper', xanchor = 'center') |>
      ## layout으로 X, Y축을 설정
      layout(xaxis = list(tickfont = list(size = 10)),
             yaxis = list(title = list(text = '확진자수')))
  ) |>
  ## 생성된 Plotly 객체들을 subplot 생성
  subplot(nrows = 3, margin = 0.04) |>
  ## 생성된 subplot의 layout 설정
  layout(showlegend = TRUE,
         title = '최근 100일간 코로나19 확진자수',
         margin = margins_R) -> subplots

subplots ##x축 공간이 부족할 때 자동으로 30도 기울기 적용 

서브플롯 범례 제거

subplots |>
  ## 범례는 제거
  layout(showlegend = FALSE)

서브플롯 배치와 편집

subplot(
  p1, p2, p3, plotly_empty(), p4, p5, plotly_empty(), p6, p7,
  ## 서브플롯은 3개의 열로 설정
  nrows = 3,
  ## 서브플롯간의 여백 설정
  heights = c(0.5, 0.25, 0.25),
  widths = c(0.5, 0.25, 0.25),
  margin = 0.04) |>
  ## 범례는 제거
  layout(showlegend = TRUE,
         ## 전체 제목 설정
         title = '최근 100일간 코로나19 확진자수',
         ## 전체 여백 설정
         margin = margins_R)
Warning: No trace type specified and no positional attributes specified
No trace type specified:
  Based on info supplied, a 'scatter' trace seems appropriate.
  Read more about this trace type -> https://plotly.com/r/reference/#scatter
No scatter mode specifed:
  Setting the mode to markers
  Read more about this attribute -> https://plotly.com/r/reference/#scatter-mode
Warning: No trace type specified and no positional attributes specified
No trace type specified:
  Based on info supplied, a 'scatter' trace seems appropriate.
  Read more about this trace type -> https://plotly.com/r/reference/#scatter
No scatter mode specifed:
  Setting the mode to markers
  Read more about this attribute -> https://plotly.com/r/reference/#scatter-mode

1행에 크게 배치

subplot(
  ## 아래의 nrows가 2이기 때문에 맨 위 열에 p1 하나를 위치시킴
  p1,
  ## subplot()으로 p2부터 p7까지를 묶어 하나의 플롯으로 만듬
  subplot(p2, p3, p4, p5, p6, p7,
          ## 서브플롯은 2개의 열로 설정함으로써 2행 3열 서브플롯 생성
          nrows = 2),
  ## 전체 서브플롯은 2열로 구성
  nrows = 2
) |>
  ## 범례 추가
  layout(showlegend = TRUE,
         ## 전체 제목 설정
         title = '최근 100일간 코로나19 확진자수',
         ## 전체 여백 설정
         margin = margins_R)

축 공유

subplot(
  p1,
  subplot(p2, p3, p4, p5, p6, p7,
          nrows = 2,
          ## shareX, shareY를 TRUE로 설정하여 축 공유
          shareX = TRUE, shareY = TRUE),
  nrows = 2, margin = 0.04
  ) |>
  layout(showlegend = TRUE,
         title = '최근 100일간 코로나19 확진자수',
         margin = margins_R)

ch6. 색상 설정

df_취업률_500 |>
  filter(졸업자수 < 500) |>
  plot_ly() |>
  add_trace(type = 'scatter', mode = 'markers',
            x = ~졸업자수, y = ~취업자수,
            color = ~취업률, colors = 'Blues') |>
  ## title 속성의 설정
  layout(title = list(text = '<b>졸업자 대비 취업자수</b>',
                      x = 0.5, xanchor = 'center', yanchor = 'top'))

Color range (colorscale)

df_취업률_500 |>
  filter(졸업자수 < 500) |>
  plot_ly() |>
  add_trace(type = 'scatter', mode = 'markers',
            x = ~졸업자수, y = ~취업자수,
            marker = list(color = ~취업률, colorscale = 'Blues',
                          cmin = 50, cmax = 100,
                          colorbar = list(title = '취업률', ticksuffix = '%'),
                          reversescale = T)
  ) |>
  ## title 속성의 설정
  layout(title = list(text = '<b>졸업자 대비 취업자수</b>',
                      x = 0.5, xanchor = 'center', yanchor = 'top'))

color=I( ), symbol=I( ) 사용

df_취업률_500 |>
  filter(졸업자수 < 500) |>
  plot_ly() |>
  add_trace(type = 'scatter', mode = 'markers',
            x = ~졸업자수, y = ~취업자수,
            color = I('darkblue'), symbol = I('circle-open')) |>
  ## title 속성의 설정
  layout(title = list(text = '<b>졸업자 대비 취업자수</b>',
                      x = 0.5, xanchor = 'center', yanchor = 'top'))

이산형 색상

df_covid19_100 |>
  group_by(location) |>
  summarise(new_cases = sum(new_cases)) |>
  plot_ly() |>
  add_trace(type = 'bar',
            x = ~location, y = ~new_cases,
            color = ~location, colors = 'Blues')

컬러 설정

df_covid19_100 |>
  group_by(location) |>
  summarise(new_cases = sum(new_cases)) |>
  plot_ly() |>
  add_trace(type = 'bar',
            x = ~location, y = ~new_cases,
            color = ~location, colors = c('darkblue', 'gray', 'gray', 'gray', 'gray', 'gray', 'gray'))