## 선형 회귀 모델 생성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)
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)