ggplot in R
※ 데이터시각화 패키지: ggplot2
- 기본 구조
- ggplot() : data와 x, y축 값을 넣어줌
- target plot() : 만들고자 하는 plot / geom_point() / geom_line() / geom_bar() 등
- geom_smooth() : 추세선
- labs() : title, x, y축 이름 설정 가능
# 기본형식
> ggplot(data, aes(x, y)) +
tartget plot() +
labs() + …
■ 기본
□ 색깔 채우기
- fill : “컬러” / “(범주형)변수” 등
# 기본형식
> ggplot(data, aes(…, fill = " "))
□ 범례 지우기
#기본형식
> +theme(legend.position = "none")
□ facet_wrap
- 변수별로 plot 분할하기
- parameter
- nrow : 각 plot이 배치될 행의 수
- ncol : 각 plot이 배치될 열의 수
- strp.position : parameter 위치 지정 (“left” / “right” / “top” / “bottom”)
- scales : plot마다 축의 범위를 다르게 보여줌(“free_x” / “free_y” / “free” 등)
# 기본형식
> +facet_wrap( ~ 변수명, nrow, ncol, strip.position, scales, ...)
# 사용예시
> df %>%
ggplot(…) +
geom_point(…) +
facet_wrap(~ 컬럼명, ncol = 2, strip.position = "bottom", scales = "free_x")
□ facet_grid
- facet_wrap과 유사하지만, 두개 이상의 변수를 입력받음
# 기본형식
> +facet_grid(y ~ x, …)
□ 추세선 그리기
- 그래프의 추세선을 추가함
- parameter
- method : 추세선 계산 방법 lm(선형회귀) / glm(일반화 선형모델) / loess(지역다항회귀) 등
- formula : 추세선을 적합시킬 때 사용할 모델 식 (ex) y~x
- se : 표준오차를 표시할지 여부 (T/F) (95%의 신뢰구간)
- col : 추세선 컬러
- linewidth : 추세선의 크기
# 기본형식
> +geom_smooth(method, formula, se, col, linewidth, ...)
# 사용예시
> df %>%
ggplot(…) +
geom_point(…) +
geom_smooth(method = "lm", se = T, col = "red", linewidth = 3)
□ X, Y축 범위 조정
# 기본형식
> +xlimc(c(최소, 최대))
> +ylimc(c(최소, 최대))
# 사용예시
> df %>%
ggplot(…) +
geom_point(…) +
xlimc(c(10, 20)) +
ylimc(c(100, 350))
□ plot 확대해서 보기
- parameter
- xlim : 확대해서 볼 x축 범위
- ylim : 확대해서 볼 y축 범위
# 기본형식
> +coord_cartesian(xlim, ylim)
# 사용예시
> df %>%
ggplot(…) +
geom_point(…) +
coord_cartesian(xlim = c(10, 20), ylim = c(100, 240))
□ 타이틀 및 서브타이틀 지정
- parameter
- title : plot 타이틀
- subtitle : plot 서브타이틀
- x : x축 이름
- y : y축 이름
# 기본형식
> +labs(title, subtitle, x, y)
□ 축 스케일링
- 변수를 scaling 하여 범위를 지정할 수 있음
- parameter
- breaks : 눈금으로 표시할 곳 지정
- limits : 그래프의 표시 범위 지정
# 기본형식
> +scale_x_continuous(breaks, limits, …)
> +scale_y_continuous(breaks, limits, …)
# 사용예시
> df %>%
ggplot(...) +
geom_histogram() +
scale_x_continuous(breaks = seq(0, 1, 0.1), limits=c(0,5)) +
scale_y_continuous(breaks = seq(10, 20, 1), limits=c(0,20))
□ 그래프 배경색 커스텀
# 기본형식
> +theme_bw()
> +theme_gray()
> +theme_minimal()
> +theme_dark()
> …
□ 격자선 커스텀
- panel.grid.major: 굵은 선 커스텀
- panel.grid.minor: 얇은 선 커스텀
# 기본형식
> +theme(panel.grid.major.x)
> +theme(panel.grid.minor.x)
> +theme(panel.grid.major.y)
> +theme(panel.grid.minor.y)
# 사용예시
> ggplot() + ... +
theme(panel.grid.major.x = element_line(color = "컬러"), # x축의 굵은 선 색깔 변경
panel.grid.minor.y = element_blank()) # y축의 얇은 선 제거
□ X, Y축 반전
# 기본형식
> +coord_flip()
# 사용예시
> df %>%
ggplot(…) +
geom_bar(…) +
coord_flip()
□ x축 이름 커스텀
- parameter
- angel : 기울일 각도
- hjust : x축 이름 높이 조절
# 기본형식
> +theme(axis.text.x = element_text(angle, hjust))
■ Box Plot (상자 그림)
# 기본구조
> ggplot(data, aes, …) + geom_boxplot()
# Box Plot 생성
## Box Plot 1개
> df %>%
ggplot(aes(col1)) +
geom_boxplot()
## 변수별 Box Plot 여러개
> df %>%
ggplot(aes(col1, col2, ...)) +
geom_boxplot()
□ 데이터 개수별 박스 크기 조절
- parameter
- varwidth = (TRUE / FALSE)
# 사용예시
> df %>%
ggplot(…) +
geom_boxplot(varwidth = T)
□ outlier 시각화 하기
- parameter
- outlier.colour = 색깔
- outlier.shape = 모양
- outlier.size = 숫자
# 사용예시
> df %>%
ggplot(…) +
geom_boxplot(outlier.colour = "red",
outlier.shape = "square",
outlier.shsize = "5")
□ boxplot에 각 데이터 표시하기
# 기본형식
> +geom_jitter()
# 사용예시
> df %>%
ggplot(…) +
geom_boxplot(...) +
geom_jitter()
□ boxplot에 수평선 및 수직선 넣기
# 수평선
> +geom_hline(yintercept)
# 수직선
> +geom_vline(xintercept)
# 사용예시
> df %>%
ggplot(…) +
geom_boxplot(...) +
geom_hline(yintercept = 숫자) +
geom_vline(xintercept = 숫자)
■ Scatter Plot (산점도)
# 기본구조
> ggplot(data, aes, …) + geom_point()
# 사용예시
> df %>%
ggplot(aes(x = x인자, y = y인자)) +
geom_point()
□ 데이터 각 포인트에 컬러 주기
# 모든 변수에 동일한 컬러 적용
> +geom_point(col = " ")
# 컬럼의 각 변수별로 다른 컬러 적용
> +geom_point(aes(col = "컬럼명"))
■ Line Chart (선 그래프)
# 기본구조
> ggplot(data, aes, …) + geom_line()
# 사용예시
> df %>%
ggplot(aes(x = x인자, y = y인자)) +
geom_line(color = " ") # 라인 컬러 추가
■ Bar Chart (막대 그래프)
# 기본구조
> ggplot(data, aes, …) + geom_bar()
> df %>%
ggplot(data, aes(x = x인자)) +
geom_bar(fill = " ", # 막대 컬러 지정
color = " ", # 막대 테두리 컬러 지정
width = " ", # 막대 너비 지정
...)
□ Bar Chart 막대 정렬
# 사용예시
> data %>%
ggplot(aes(x = reorder(x인자, (asc/desc)))) +
geom_bar()
□ Bar Chart 막대 겹치기
- parameter
- position : “identity” / …
■ Pie Chart (파이 차트)
- 막대그래프 후 coord_polar(…) 추가
# 사용예시
> ggplot(data, aes) +
geom_bar() +
coord_polar()
■ Histogram (히스토그램)
- parameter
- bins : 막대의 개수(구간) 지정
- binwidth : 막대의 폭 지정(나눌 범위)
- fill : 막대 컬러 / 범주별로 컬러 다르게 하고자 하는 경우. (position = “identity”와 함께 써야 좋다)
- col = 테두리 색깔
- alpha : 막대의 투명도 (겹칠때 사용)
# 기본구조
> ggplot(aes(x)) +
geom_histogram()
# 사용예시
> df %>%
ggplot(aes(…) +
geom_histogram(bins = 숫자, binwidth = 숫자, fill = "컬러", col = "컬러", alpha = 숫자))
□ Histogram 그래프 겹치기
- parameter
- position : “identity” / …
# 사용예시
> df %>%
ggplot(aes(x = x인자, fill = factor(변수)) +
geom_histogram(position = "identity"))
□ 막대 색깔 / 범례 수정
- parameter
- value : 채우기 색상 지정
- break : 범례 항목 지정
- labels : 범례 타이틀
# 기본형식
> +scale_fill_manual(…)
# 사용예시
> df %>%
ggplot(...) +
geom_histogram() +
scale_fill_manual(values = c("4" = "blue", "f" = "green"),
breaks = c("4", "f"),
labels = c("front-wheel", "rear-wheel"))
댓글남기기