데이터 분석/R

앤디 필드의 유쾌한 R 통계학 챕터 4 - 기초 시각화

쎄마비 2022. 4. 1. 15:00
728x90
반응형

 

챕터 4에서는 ggplot2를 사용하여 여러 가지 그래프를 그리는 방법을 배운다.

 

rm(list=ls())

# 이번 챕터에서는 ggplot2를 사용한다.
library(ggplot2)

# 그래프는 기하 객체(geom), 미적 속성(aes)로 구성된다.
# 자주 쓰이는 geom
geom_bar() # 선 그리기
geom_point() # 점 그리기
geom_line() # 자료를 잇는 직선 그리기
geom_smooth() # 자료 전체를 요약하는 직선 그리기
gem_histogram() # 히스토그램 그리기
geom_boxplot() # 박스플롯 그리기
geom_text() # 텍스트 넣기
geom_density() # 밀도 그래드 그리기
geom_errorbar() # 오차 막대 그리기
geom_vline() # 수직선 그리기
geom_hline() # 수평선 그리기


# 테스트용 데이터프레임 불러오기
facebookData <- read.delim('datafiles/FacebookNarcissism.dat', header = TRUE);facebookData

# 그래프 객체 만들기 theme()에서 제목도 지정했다.
graph <- ggplot(facebookData, aes(NPQC_R_Total, Rating)) + theme(title = element_text('fb'))

# 객체에 기하 객체 점 추가 shape는 모양, size는 크기, colour는 색, position은 위치를 조정한다
graph + geom_point(shape = 17, size = 3, aes(colour = Rating_Type), position = 'jitter')

# aes 안의 값은 해당값 별로 속성을 다르게 표현하도록 한다. 예시에서는 Rating_Type에 따라 색, 모양이 다르다.
# position은 서로 겹치지 않도록 위치를 조정하기 위해 사용한다.
graph + geom_point(size = 3, aes(colour = Rating_Type, shape = Rating_Type), position = 'jitter')


# 산점도 테스트용 데이터프레임 불러오기
examData <- read.delim('datafiles/Exam Anxiety.dat', header = TRUE);examData

# 그래프 객체 만들기
scatter <- ggplot(examData, aes(Anxiety, Exam, colour = Gender))
scatter + geom_point() + labs(x= 'Eaxm Anxiety', y= 'Performance', colour = 'Gender')

# smoother를통해 평활기 그리기(geom_smooth)
scatter + geom_point() + labs(x= 'Eaxm Anxiety', y= 'Performance', colour = 'Gender') + geom_smooth()
# smoother를통해 회귀선 그리기(method = 'lm')
scatter + geom_point() + labs(x= 'Eaxm Anxiety', y= 'Performance', colour = 'Gender') + geom_smooth(method= 'lm', colour = 'Red')
# smoother를통해 95% 신뢰구간 없는 회귀선 그리기(se = F)
scatter + geom_point() + labs(x= 'Eaxm Anxiety', y= 'Performance', colour = 'Gender') + geom_smooth(method= 'lm', se = F)
# smoother를통해 회귀선 그리기 + 신뢰구간에 미적 속성 투명도와 색상 추가하기(fill, alpha)
scatter + geom_point() + geom_smooth(method= 'lm',  aes(fill = Gender), alpha = 0.1) + labs(x= 'Eaxm Anxiety', y= 'Performance', colour = 'Gender') 


# 히스토그램 테스트용 데이터 불러오기
festivData <- read.delim('datafiles/DownloadFestival.dat', header = TRUE)

# 그래프 객체 만들기
festivalHisto <- ggplot(festivData, aes(day1)) 
# 히스토그램 만들고 범례 제거하기(legend.position = 'None')
festivalHisto + geom_histogram() + theme(legend.position = 'none')
# 히스토그램 너비 지정하고 레이블명 추가하기(binwidth)
festivalHisto + geom_histogram(binwidth = 0.4) + theme(legend.position = 'none') + labs(x = 'Hygeine', y = 'Frequency')


# 박스플롯용 그래프 객체 만들기
festivalBoxplot <- ggplot(festivData, aes(gender, day1)) 
festivalBoxplot + geom_boxplot() + labs(x = 'Gender', y = 'Hygeine')

# 데이터 정렬해서 이상치 찾고 제거(이상치가 하나 존재하므로 마지막 행만 삭제하였다.)
festivData <- festivData[order(festivData$day1),]
festivData[length(festivData$ticknumb), ]
festivData <- festivData[-length(festivData$ticknumb),]

# 박스플롯 다시 확인
festivalBoxplot <- ggplot(festivData, aes(gender, day1)) 
festivalBoxplot + geom_boxplot() + labs(x = 'Gender', y = 'Hygeine')


# 밀도 플롯(density plot) 그리기
density <- ggplot(festivData, aes(day1))
density + geom_density() + labs(x = 'Hygiene', y = 'Density Esttimate')


# 막대 그래프 그리기
chickFlick <- read.delim('datafiles/chickflick.dat', header = TRUE)
bar <- ggplot(chickFlick, aes(film, arousal, fill = gender))

# 막대 그래프는 여러 측정 값이 모두 표시되는게 아니라 대푯값이 사용된다. 따라서 fun = mean과 같이 어떤 값을 사용할 지 지정해야 한다.
bar + stat_summary(fun = mean, geom = 'bar', position = 'dodge')

# 막대 그래프에 오차 범위 추가하기 (stat_summary(fun.data = , geom = 'errorbar'...)
bar + stat_summary(fun = mean, geom = 'bar', position = 'dodge') + stat_summary(fun.data = mean_cl_normal, geom = 'errorbar', position = position_dodge(width = 0.8), width = 0.2) + labs(x= 'Film', y= 'Mean Arousal', fill = 'Gender')


# 면 분할하기(facet_wrap(~변수명))
bar2 <- ggplot(chickFlick, aes(film, arousal, fill = film))
bar2 + stat_summary(fun = mean, geom = 'bar') + stat_summary(fun.data = mean_cl_normal, geom = 'errorbar', width = 0.2) + facet_wrap(~gender) + labs(x = 'Film', y = 'Mean Arousal') + theme(legend.position = 'none')


# 선 그래프 그리기
# 데이터를 불러오고 적절한 형식으로 변경한다.(딸꾹질 수, 처치방법(요인) 형식)
hiccupsData <- read.delim('datafiles/Hiccups.dat', header = TRUE)
hiccups <- stack(hiccupsData)
names(hiccups) <- c('Hiccups', 'Intervention')
hiccups$Intervention_Factor <- factor(hiccups$Intervention, levels(hiccups$Intervention))

# 그래프 객체 만들기
line <- ggplot(hiccups, aes(Intervention_Factor, Hiccups))
line + stat_summary(fun = mean, geom = 'line', aes(group = 1)) # 이 때 aes(group = 1)이 꼭 필요하다
line + stat_summary(fun = mean, geom = 'line', aes(group = 1), colour = 'blue', linetype = 'dashed') + stat_summary(fun.data = mean_cl_boot, geom = 'errorbar', width = 0.1) + labs(x = 'Intervention', y = 'Mean Hiccups')


# 여러 독립 변수에 대한 선 그래프 그리기
# 데이터를 불러오고 형식을 확인한 후 적절한 형식으로 변경한다.(그룹, 측정시기, 점수 형식)
textData <- read.delim('datafiles/textmessages.dat', header = TRUE)
textData[c(1:10),]

library(reshape)
textMessages <- melt(textData, id = 'Group')
names(textMessages) <- c('Group', 'Time',  'Grammar_Score')
textMessages

# 그래프 객체를 만들기
line2 <- ggplot(textMessages, aes(Time, Grammar_Score, colour = Group))
line2 + stat_summary(fun = mean, geom = 'line', aes(group = Group)) + stat_summary(fun.data = mean_cl_boot, geom = 'errorbar', width = 0.2) + labs(x = 'Time', y = 'Mean Grammar Score', colour = 'Group') + theme_bw()

 

728x90
반응형