pl_part3_ch7

관계와 분포의 시각화

데이터 불러오기, plotly setting

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)

산점도

  • add_marker 사용
df_취업률_500 |>
  plot_ly() |>
  ## add_markers()로 marker mode의 scatter 트레이스 추가
  add_markers(x = ~졸업자수, y = ~취업자수, color = ~대계열) |>
  layout(title = list(text = '<b>졸업자 대비 취업자수</b>', font = list(color = 'white')),
         margin = margins_R,
         paper_bgcolor = 'black', plot_bgcolor = 'black',
         xaxis = list(color = 'white', ticksuffix = '명'),
         yaxis = list(color = 'white', gridcolor = 'gray', ticksuffix = '명', dtick = 100),
         legend = list(font = list(color = 'white')))
  • add_trace 사용
df_취업률_500 |>
  plot_ly() |>
  ## add_trace()로 marker mode의 scatter 트레이스 추가
  add_trace(type = 'scatter', mode = 'markers',
            x = ~졸업자수, y = ~취업자수, color = ~대계열) |>
  layout(
    ## 제목 설정
    title = list(text = '<b>졸업자 대비 취업자수</b>', font = list(color = 'white')),
    margin = margins_R, ## 여백 설정
    paper_bgcolor = 'black', plot_bgcolor = 'black', ## 여백 설정
    xaxis = list(color = 'white', ticksuffix = '명'), ## X축 설정
    ## Y축 설정
    yaxis = list(color = 'white', gridcolor = 'gray', ticksuffix = '명', dtick = 100),
    legend = list(font = list(color = 'white'))) ## 범례 설정
  • 추세선 추가하기
## 선형 회귀 모델 생성
lm_trend <- lm(data = df_취업률_500, 취업자수 ~ 졸업자수)

## 국소 회귀 모델 생성
loess_trend <- loess(data = df_취업률_500, 취업자수 ~ 졸업자수)
## 국소 회귀 모델 데이터 생성
df_loess_trend <- data.frame(X = df_취업률_500$졸업자수, Y = fitted(loess_trend)) |>
  arrange(X) ##x축 순서대로 데이터 정렬을 위한 임시 데이터 프레임

##
df_취업률_500 |>
  plot_ly(type = 'scatter', mode = 'markers') |>
  add_trace(x = ~졸업자수, y = ~취업자수, showlegend = FALSE) |>
  ## 선형 회귀 데이터를 사용하여 line mode scatter 트레이스 생성
  add_trace(mode = 'lines', x = ~졸업자수, y = ~fitted(lm_trend),
            name = '선형 추세선', line = list(dash = 'dot')) |>
  ## 국소 =회귀 데이터를 사용하여 line mode scatter 트레이스 생성, loess(local regression)는 데이터 구간별로 회귀를 수행하여 국소적인 변화를 반영.비선형임.
  add_trace(data = df_loess_trend, mode = 'lines',
            x = ~X, y = ~Y, name = 'loess 추세선')
  • ggplot() 으로 먼저 그린 후에 plotly로 전환 (세부 그룹별 추세선 추가시 사용)
p <- df_취업률_500 |>
  ggplot(aes(x = 졸업자수, y = 취업자수, color = 대계열)) +
  geom_point() +
  ## geom_smooth로 선형회귀 추세선 추가
  geom_smooth(method = 'lm', se = FALSE) +
  ## geom_smooth로 국소 회귀 추세선 추가, dash 
  geom_smooth(method = 'loess', se= FALSE, linetype = 2)

## ggplot2 객체를 Plotly로 전환
ggplotly(p)
`geom_smooth()` using formula = 'y ~ x'
`geom_smooth()` using formula = 'y ~ x'

버블 차트

df_covid19_stat |>
  plot_ly() |>
  add_trace(type = 'scatter', mode = 'markers',
            x = ~백신접종완료율, y = ~인구백명당부스터접종자수,
            ## marker의 사이즈를 사용해 버블 차트 구현
            marker = list(size = ~십만명당사망자수, opacity = 0.5, sizemode = 'area')
  )
Warning: Ignoring 35 observations

히스토그램

## 취업률 데이터를 사용해 Plotly 객체 생성
p_histogram <- df_취업률_500 |> plot_ly()

p_histogram |>
  ## histogram trace로 X축을 취업률로 매핑, name을 취업률로 설정
  add_histogram(x = ~취업률, name = '취업률',
                ## xbins 속성 설정
                xbins = list(start = 0, end = 100, size = 2.5)) |>
  ## 제목과 여백 설정
  layout(title = '취업률 histogram', margin = margins_R)
  • 오버레이 히스토그램
p_histogram <- df_취업률_500 |> plot_ly()

p_histogram |>
  ## histogram trace로 X축을 취업률로 매핑, name을 취업률로 설정
  add_histogram(x = ~취업률, color = ~과정구분, opacity = 0.4,
                xbins = list(size = 5)) |>
  layout(title = '취업률 histogram',
         ## histogram barmode를 "overlay"로 설정
         barmode = "overlay",
         margin = margins_R)
  • 누적 히스토그램
p_histogram <- df_취업률_500 |> plot_ly()
p_histogram |>
  add_histogram(x = ~취업률, name = '취업률',
                xbins = list(start = 0, end = 100, size = 2.5),
                ## 누적 히스토그램 설정
                cumulative = list(enabled=TRUE)) |>
  layout(title = '취업률 histogram', margin = margins_R)
  • 히스토그램 함수 사용 (sum, avg, max 등으로 y 축에 표현)
p_histogram |>
  add_trace(type = 'histogram', ## add_histogram()과 동의 함수
            x = ~대계열,
            ## 히스토그램 막대 함수를 'count'로 설정
            histfunc = 'count') |>
  layout(title = '취업률 histogram',
         yaxis = list(title = list(text = '학과수')),
         margin = margins_R)
#################
p_histogram |>
  add_trace(type = 'histogram', x = ~대계열, y = ~as.character(취업률),
            ## 히스토그램 막대 함수를 'sum'으로 설정
            histfunc = 'sum') |>
  ## Y축을 선형으로 설정
  layout(yaxis=list(type='linear',title = list(text = '취업률 합계')),
         title = '취업률 histogram',
         margin = margins_R)
#################
p_histogram |>
  add_trace(type = 'histogram', x = ~대계열, y = ~as.character(취업률),
            ## 히스토그램 막대 값을 'average'로 설정
            histfunc = 'avg') |>
  ## Y축을 선형으로 설정
  layout(yaxis=list(type='linear',title = list(text = '취업률 평균')),
         title = '취업률 histogram',
         margin = margins_R)
#################
p_histogram |>
  add_trace(type = 'histogram', x = ~대계열, y = ~as.character(취업률),
            ##히스토그램 막대 값을 'max'로 설정
            histfunc = 'max') |>
  ## Y축을 선형으로 설정
  layout(yaxis=list(type='linear',title = list(text = '취업률 최대값')),
         title = '취업률 histogram',
         margin = margins_R)

박스 플릇

df_취업률 |>
  plot_ly() |>
  ## box 트레이스 생성
  add_boxplot(x = ~대계열, y = ~취업률_계)|>
  layout(title = list(text = '대학 계열별 취업률 분포'),
         margin = margins_R)
  • 평균, 표준편차가 포함된 박스 플롯
df_취업률 |>
  plot_ly() |>
  add_boxplot(x = ~대계열, y = ~취업률_계,
              ## boxmean과 notched 설정
              boxmean = 'sd', notched = TRUE)|>
  layout(title = list(text = '대학 계열별 취업률 분포'),
         margin = margins_R)
  • 여러 개의 박스 플롯
df_취업률 |>
  plot_ly() |>
  add_boxplot(x = ~대계열, y = ~취업률_계,
              ## color를 과정구분으로 매핑
              color = ~과정구분)|>
  ## boxmode를 group으로 설정
  layout(boxmode = "group", title = list(text = '대학 계열별 취업률 분포'),
         margin = margins_R)
  • Jitter box plot
fig <- df_covid19_100_wide |> plot_ly()

## 대륙별 확진자 box 트레이스 생성
fig <- fig |>
  add_boxplot(y = ~확진자_한국, name = '한국',
              ## boxpoints, jitter, pointpos 설정
              boxpoints = "all", jitter = 0.3, pointpos = -1.8)

fig <- fig |>
  add_boxplot(y = ~확진자_아시아, name = '아시아',
              boxpoints = "all", jitter = 0.3, pointpos = -1.8)

fig <- fig |>
  add_boxplot(y = ~확진자_유럽, name = '유럽',
              boxpoints = "all", jitter = 0.3, pointpos = -1.8)

fig <- fig |>
  add_boxplot(y = ~확진자_북미, name = '북미',
              boxpoints = "all", jitter = 0.3, pointpos = -1.8)

fig <- fig |>
  add_boxplot(y = ~확진자_남미, name = '남미',
              boxpoints = "all", jitter = 0.3, pointpos = -1.8)
fig <- fig |>
  add_boxplot(y = ~확진자_아프리카, name = '아프리카',
            boxpoints = "all", jitter = 0.3, pointpos = -1.8)

fig <- fig |>
  add_boxplot(y = ~확진자_오세아니아, name = '오세아니아',
              boxpoints = "all", jitter = 0.3, pointpos = -1.8) #박스좌측에 박스 넓이 1.8배

fig |> layout(title = list(text = '한국 및 대륙별 일별 확진자 분포'),
              xaxis = list(title = '대륙명'),
              yaxis = list(title = '확진자수(명)'),
              margin = margins_R,
              paper_bgcolor='lightgray', plot_bgcolor='lightgray')

바이올린 플롯

df_취업률_500 |>
  plot_ly() |>
  ## violin 트레이스 추가
  add_trace(type = 'violin', x = ~대계열, y = ~취업률) |>
  layout(title = list(text = '대학 계열별 취업률 분포'),
         margin = margins_R)
  • 평균선 포함 바이올린 플롯
df_취업률_500 |>
  plot_ly() |>
  ## 바이올린 trace 추가
  add_trace(type = 'violin', x = ~대계열, y = ~취업률,
            ## 바이올린 내부 박스 표시
            box = list(visible = TRUE),
            ## 평균 선 표시
            meanline = list(visible = TRUE)) |>
  layout(title = list(text = '대학 계열별 취업률 분포'),
         margin = margins_R)
  • 분리된 플롯
df_취업률_500 |>
  plot_ly() |>
  ## 대학과정을 필터링한 데이터 설정
  add_trace(data = df_취업률_500 |> filter(과정구분 == '대학과정'),
            ## 바이올린 trace로 추가
            type = 'violin', x = ~대계열, y = ~취업률, name = '대학',
            ## side, box의 설정
            side = 'positive', box = list(visible = TRUE, width = 0.5),
            ## meanline의 속성 설정
            meanline = list(visible = TRUE, width = 1)) |>
  ## 전문대학과정을 필터링한 데이터 설정
  add_trace(data = df_취업률_500 |> filter(과정구분 == '전문대학과정'),
            type = 'violin', x = ~대계열, y = ~취업률, name = '전문대학',
            side = 'negative', box = list(visible = TRUE, width = 0.5),
            meanline = list(visible = TRUE, width = 1)) |>
  ## violonemode 설정
  layout(violinmode = "overlay",
         title = list(text = '대학 계열별 취업률 분포'),
         margin = margins_R)
Warning: 'layout' objects don't have these attributes: 'violinmode'
Valid attributes include:
'_deprecated', 'activeshape', 'annotations', 'autosize', 'autotypenumbers', 'calendar', 'clickmode', 'coloraxis', 'colorscale', 'colorway', 'computed', 'datarevision', 'dragmode', 'editrevision', 'editType', 'font', 'geo', 'grid', 'height', 'hidesources', 'hoverdistance', 'hoverlabel', 'hovermode', 'images', 'legend', 'mapbox', 'margin', 'meta', 'metasrc', 'modebar', 'newshape', 'paper_bgcolor', 'plot_bgcolor', 'polar', 'scene', 'selectdirection', 'selectionrevision', 'separators', 'shapes', 'showlegend', 'sliders', 'smith', 'spikedistance', 'template', 'ternary', 'title', 'transition', 'uirevision', 'uniformtext', 'updatemenus', 'width', 'xaxis', 'yaxis', 'boxmode', 'barmode', 'bargap', 'mapType'