Data Analysis

R/ggplot2(시각화)

[R] 고급시각화 실습 (2)

Holy_Water 2022. 11. 24. 17:32

기하학적 기법 시각화

 

일반 그래픽 관련 패키지: 이미지 표현에 중점
ggplot2: 기하학적 객체(점, 선, 막대 등)에 미적 특성(색상, 모양, 크기)을 연결. 데이터 객체와 그래픽 객체를 서로 분리하고 재사용 가능. 
ggplot2패키지의 주요 함수
qplot(), ggplot(), ggsave()

 

 

실습 (ggplot2 패키지설치와 실습 데이터 가져오기)

install.packages("ggplot2")
library(ggplot2)
data(mpg)
str(mpg)
head(mpg)
summary(mpg)
table(mpg$drv)

mpg데이터 사용

 

 

실습 (qplot()함수의 fill과 binwidth 속성 적용)

qplot(hwy, data = mpg, fill = drv, binwidth = 2)

qplot()함수 형식: qplot(x축 ~ y축, data, facet, geom, stat, position, xlim, ylim, log, main, xlab, ylab, asp)

 

 

실습 (diamonds 데이터 셋에 막대, 점, 선 레이아웃 적용하기)

실습용 데이터 셋 확인하기, geom속성과 fill속성 사용

head(diamonds)
qplot(clarity, data = diamonds, fill = cut, geom = "bar")

 

 

산점도 그래프 그리기

qplot(wt, mpg, data = mtcars, size = qsec, 
 color = factor(carb),
 shape = factor(cyl), geom = "point")

 

산점도 그래프의평활에 cyl변수의 요인으로 색상 적용하기

qplot(wt, mpg, dat = mtcars, color = factor(cyl), 
 geom = c("point", "smooth"))

 

geom=”line” 속성으로 그래프 그리기

qplot(mpg, wt, data = mtcars, 
 color = factor(cyl), geom = "line")

 

geom=c(“point”, “line”)속성으로 그래프 그리기

qplot(mpg, wt, data = mtcars, 
 color = factor(cyl), geom = c("point", "line"))

 

 

ggplot()함수

ggplot()함수는 데이터 속성에 미적요소를 매핑한 후 스케일링과정을 거쳐서 생성된 객체를 + 연산자를 사용하여 미적 요소 맵핑을 새로운 레이어에 상속받아 재사용할 수 있도록 지원하는 ggplot2 패키지의 함수

 

ggplot()함수는 다음의 순서에 따라 그래프를 그린다.
1) 미적요소 맵핑(aes): x 축, y 축, color속성
2) 통계적인 변환(stat): 통계계산 작업
3) 기하학적 객체 적용(geom): 차트 유형
4) 위치조정(position, adjustment), 채우기(fill), 스택(stack), 닷지(dodge) 유형

 

실습 (stat_bin()함수 적용 영역과 산점도 그래프 그리기)

1단계: stat_bin()함수 적용 영역 나타내기

p <- ggplot(diamonds, aes(price))
p + stat_bin(aes(fill = cut), geom = "area")

 

2단계: stat_bin()함수로 산점도 그래프 그리기

p + stat_bin(aes(color = cut, 
 size = ..density..), geom = "point")

 

 

산점도와 회귀선 적용
회귀선을 시각화하기 위해
geom_count()함수: 숫자의 크기에 따라서 산점도를 시각화
geom_smooth()함수: 속성으로 method=”lm”을 지정하면 회귀선과 보조선으로 시각화
사용.

 

실습 (산점도에 회귀선 적용하기)

library(UsingR)
data("galton")
p <- ggplot(data = galton, aes(x = parent, y = child))
p + geom_count() + geom_smooth(method ="lm")

 

 

실습 (테마를 적용하여 그래프 외형 속성 설정)

 

1단계: 제목을 설정한 산점도 그래프

p <- ggplot(diamonds, aes(carat, price, color = cut))
p <- p + geom_point() + ggtitle("다이아몬드 무게와 가격의 상관관계")
print(p)

 

2단계: theme()함수를 이용하여 그래프의 외형 속성 적용

p + theme(
 title = element_text(color = "blue", size = 25), 
 axis.title = element_text(size = 14, face ="bold"),
 axis.title.x = element_text(color = "green"),
 axis.title.y = element_text(color = "green"),
 axis.text = element_text(size = 14),
 axis.text.y = element_text(color = "red"),
 axis.text.x = element_text(color = "purple"),
 legend.title = element_text(size = 20,
 face = "bold",
color = "red"),
 legend.position = "bottom",
 legend.direction = "horizontal"
)