일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
- ggsurvplot
- 카플란마이어
- CrossValidation
- R문법
- R
- R select
- 데이터 핸들링
- R mutate
- R filter
- ISLR
- 생존그래프
- 강화학습 #추천서적 #강화학습인액션
- 미국 선거데이터
- geom_errorbar
- 데이터핸들링
- 주식데이터시각화
- R 연습문제
- R ggplot2
- ggplot()
- 콕스비례모형
- 이산형 확률분포
- 의사결정나무
- 생존분석
- 교차타당성
- R 결측치
- dplyr
- Bias-Variance Tradeoff
- R dplyr
- 확률실험
- ggplot2
- Today
- Total
Must Learning With Statistics
9. ggplot2를 활용한 다양한 그래프 그리기 본문
Chapter9. ggplot2를 활용한 다양한 그래프 그리기
이번 장에서는 ggplot2로 그릴 수 있는 그래프들의 종류에 대해 알아보도록 하겠습니다.
library(ggplot2)
library(dplyr)
STOCK = read.csv("D:\\Dropbox\\DATA SET(Dropbox)\\uniqlo.csv")
STOCK$Date = as.Date(STOCK$Date)
STOCK$Year = as.factor(format(STOCK$Date,"%Y"))
STOCK$Day = as.factor(format(STOCK$Date,"%a"))
Group_Data = STOCK %>%
group_by(Year,Day) %>%
dplyr::summarise(Mean = round(mean(Open)),
Median = round(median(Open)),
Max = round(max(Open)),
Counts = length(Open))
1. Bar Chart
막대도표는 가장 기본적인 그래프입니다. 하나의 이산형 변수에 대해 시각화를 하는 그래프입니다. 기본적으로 y축은 따로 설정할 필요는 없습니다.
- 하나의 이산형 변수를 기준으로 x축 변수 1개로만 그리는 경우
ggplot(Group_Data) +
geom_bar(aes(x = as.factor(Counts),fill = ..count..)) +
xlab("") + ylab("") +
scale_fill_gradient(low = "#CCE5FF", high = "#FF00FF") +
theme_classic() + ggtitle("Continuous Color")
ggplot(Group_Data) +
geom_bar(aes(x = as.factor(Counts),fill = Day),alpha = 0.4) +
xlab("") + ylab("") +
theme_classic() + ggtitle("Discrete Color")
)
- 색 구분 포지션을 변경하고 싶은 경우
ggplot(Group_Data) +
geom_bar(aes(x = as.factor(Counts),fill = Day),
alpha = 0.4,position = "dodge") +
xlab("") + ylab("") +
theme_classic() + ggtitle("Discrete Color\n position Dodge")
- x축, y축 1개씩 총 변수 2개로 그리는 경우, stat = ‘identity’ 사용합니다.
ggplot(Group_Data) +
geom_bar(aes(x = Year, y = Mean, fill = Day), stat = 'identity') +
scale_fill_manual(values = c("#C2DAEF","#C2EFDD","#BBAAE9",
"#E9F298","#FABDB3")) +
theme_classic()
2. Histogram
히스토그램은 막대도표와 매우 비슷하게 생겼지만, 연속형 변수를 시각화 하는 점에서 막대도표와 큰 차이점을 지니고 있습니다. 연속형 변수에 대해 구간을 나누어, 막대도표처럼 집계 된 값을 출력하여 그래프를 그립니다. 여기서 히스토그램의 변수 구간을 조정하는 명령어는 binwidth를 활용합니다.
ggplot(STOCK) +
geom_histogram(aes(x = High , fill = ..x.. ),
binwidth = 1000) +
scale_fill_gradient(low = "#CCE5FF", high = "#FF00FF") +
theme_classic() + labs(fill = "Labels Name")
ggplot(STOCK) +
geom_histogram(aes(x = High , fill = Day ),
binwidth = 1000, alpha = 0.4) +
theme_classic() + labs(fill = "Labels Name")
)
ggplot(STOCK) +
geom_histogram(aes(x = High , fill = Day ),
binwidth = 1000, alpha = 0.4, position = "dodge") +
theme_classic() + labs(fill = "Labels Name")
3. Density plot
히스토그램과 비슷하게 작성합니다. 그래프 면적이 각각의 비율이 되도록 맞추어줍니다.
ggplot(STOCK) +
geom_density(aes(x = High)) +
theme_classic() + labs(fill = "Labels Name")
ggplot(STOCK) +
geom_density(aes(x = High , fill = Day ),alpha = 0.4) +
theme_classic() + labs(fill = "Labels Name") +
theme(axis.text.x = element_text(size = 9, angle = 45,
hjust = 1))
)
4. Boxplot & Jitter plot
박스플롯은 데이터를 요약하는데에 있어 매우 유용한 그래프입니다. 먼저, 박스플롯에 대해 이해를 하실 필요가 있습니다. 박스플롯은 분위수(quantile)로 작성이 됩니다. 상자 내부에 위치한 줄은 중위수(Median)를 의미합니다. 상자의 밑변, 윗변은 각각 1, 3분위수를 의미합니다. 상자를 감싸는 테두리는 울타리라고 합니다. 이 선을 벗어나면, 주로 이상치(Outlier)라고 합니다.
박스플롯을 그리기 위해서 x축은 Descrete 변수를, y축에는 Continuous 변수를 배치해야합니다.
ggplot(STOCK) +
geom_boxplot(aes(x = Day, y = Volume, fill = Day),
alpha = 0.4, outlier.color = 'red') +
theme_bw()
ggplot(STOCK) +
geom_boxplot(aes(x = Day, y = Volume, fill = Day),
alpha = 0.2, outlier.color = 'red') +
geom_jitter(aes(x= Day, y= Volume,col = Day),alpha = 0.1) +
theme_bw()
)
5. Violin plot
박스플롯과 비슷한 역할을 수행합니다.
ggplot(STOCK) +
geom_violin(aes(x = Day, y = Volume, fill = Day),
alpha = 0.4) +
theme_bw()
6. Scatter plot
산점도는 데이터의 상관관계를 파악하기에 매우 유용한 그래프입니다. 그래프에서 shape, size 등을 통해 다양한 그래프를 그릴 수가 있습니다.
ggplot(STOCK) +
geom_point(aes(x = Open, y = Stock.Trading,
col = High, size = log(Volume), shape = Year)) +
scale_color_gradient(low = "#CCE5FF", high = "#FF00FF") +
scale_shape_manual(values = c(19,20,21,22,23)) +
labs(
col = "Color", shape = "Shape", size = "Size"
) +
theme_bw() +
theme(axis.text.x = element_blank())
7. Smooth plot
geom_smooth는 회귀선을 그려줍니다.
ggplot(STOCK) +
geom_smooth(aes(x = Open, y = Stock.Trading),
method = 'lm',
col = '#8A8585') +
theme_bw()
ggplot(STOCK) +
geom_point(aes(x = Open, y = Stock.Trading, ),col = 'royalblue', alpha = 0.2) +
geom_smooth(aes(x = Open, y = Stock.Trading),
method = 'lm',
col = '#8A8585') +
theme_bw()
)
8. abline, vline, hline
그래프에 평행선, 수직선, 대각선을 그릴 수 있는 명령어입니다.
ggplot(NULL) +
geom_vline(xintercept = 10, linetype = 'dashed',
col = 'royalblue', size = 3) +
geom_hline(yintercept = 10, linetype = 'dashed',
col = 'royalblue', size = 3) +
geom_abline(intercept = 0, slope = 1, col = 'red',
size = 3) +
theme_bw()
9. Step plot
계단 형식의 그래프로, 값의 증가량을 나타낼 때 효과적입니다.
Hazard_Ratio = c(0.1,0.3,0.4,0.45,0.49,0.52,0.6,0.65,0.75,0.8,0.95)
Survival_Time = c(1,2,3,4,5,6,7,8,9,10,11)
ggplot(NULL) +
geom_step(aes(x = Survival_Time, y = Hazard_Ratio),col = 'red') +
scale_x_continuous(breaks = Survival_Time) +
theme_classic()
10. Density 2d plot
밀도그래프를 2개의 차원으로 그리는 그래프입니다.
ggplot(STOCK) +
geom_point(aes(x= log(Stock.Trading), y = Open, col = Open)) +
geom_density2d(aes(x= log(Stock.Trading), y = Open)) +
scale_color_gradient(low = "#E93061", high = "#574449") +
theme_bw()
11. Text plot
산점도와 거의 동일합니다. 다만, 그냥 점이 아닌 지정한 글자로 그래프를 그리는 방식입니다.
SL = sample(1:nrow(STOCK), 200, replace = FALSE)
ggplot(STOCK[SL,]) +
geom_text(aes(x = Date , y= Open, label = Open,
col = Open), size = 2) +
scale_color_gradient(low = "#CCE5FF", high = "#0080FF") +
theme_bw()
12. Line plot & Timeseries plot
선 그래프에서는 group이라는 옵션이 필요합니다.
ggplot(STOCK) +
geom_line(aes(x= Year, y = Open),group = 1) +
theme_bw()
이런 경우 선 그래프는 잘못 그려진 경우입니다. 그 이유는 선은 동일한 x에서 하나의 y값만을 가져야하는 특징을 지니고 있습니다. 그러니 선 그래프를 그리기 전에는 항상 이 점을 유의해서 요약값을 만들어 준 후, 그래프를 작성해야 합니다.
ggplot(STOCK) +
geom_line(aes(x = Date, y = Open), group = 1) +
theme_bw()
ggplot(STOCK) +
geom_line(aes(x = Date, y = Open,
col = Year, group = Year)) +
theme_bw()
)
13. Error bar plot
우리가 직접 범위를 조정할 수 있는 오차범위 그래프입니다. 학술 저널에서는 꽤나 잘 쓰이는 그래프입니다. 일반적으로 point, boxplot과 혼합할 때 주로 쓰입니다.
DF = STOCK %>%
group_by(Year) %>%
summarise(Min = min(High),
Max = max(High))
ggplot(NULL) +
geom_boxplot(data = STOCK, aes(x = Year, y = High, fill = Year)) +
geom_errorbar(data = DF, aes(x = Year, ymin = Min, ymax = Max)) +
theme_classic()
14. Corrplot
상관계수를 히트맵 형식으로 한 그래프입니다.
Cor_matrix = cor(iris[,1:4]) # iris는 R 기본 내장 데이터
library(corrplot)
corrplot(Cor_matrix , method = "color", outline = T, addgrid.col = "darkgray",
order="hclust", addrect = 4, rect.col = "black",
rect.lwd = 5,cl.pos = "b", tl.col = "indianred4",
tl.cex = 1, cl.cex = 1, addCoef.col = "white",
number.digits = 2, number.cex = 1,
col = colorRampPalette(c("darkred","white","midnightblue"))(100))
15. Heatmap
위 Corrplot과 비슷한 형태의 그래프입니다. 원하는 값을 기준으로 색의 온도를 나타낼 수가 있습니다.
ggplot(Group_Data) +
geom_tile(aes(x = Year, y = Day, fill = Counts),alpha = 0.6) +
scale_fill_gradient(low = "#C2DAEF", high = "#8A8585") +
theme_classic()
16. Ribbon plot
범위를 정할 수 있는 선 그래프입니다.
ggplot(STOCK) +
geom_ribbon(aes(x= Date, ymin = log(Low) - 0.5, ymax = log(High) + 0.5),fill = 'royalblue' , alpha = 0.2) +
theme_classic()
ggplot(STOCK) +
geom_ribbon(aes(x= Date, ymin = log(Low) - 0.5, ymax = log(High) + 0.5),fill = 'royalblue' , alpha = 0.2) +
geom_point(aes(x= Date, y = log(Low) - 0.5), col = '#8A8585', alpha = 0.8) +
geom_point(aes(x= Date, y = log(High) + 0.5), col = '#8A8585', alpha = 0.8) +
geom_line(aes(x = Date, y = log(Open)),group =1 , col = '#C2DAEF' , linetype = 'dashed', size = 0.1) +
geom_point(aes(x = Date, y = log(Open)),col = 'red', alpha = 0.4) +
theme_classic() +
ylab("") + xlab("")
)
17. Ridge plot
density plot을 여러개 그릴 수 있는 그래프입니다.
library(ggridges)
ggplot(STOCK) +
geom_density_ridges_gradient(aes(x = log(High) + 0.2 , y= Year, fill = ..x..),gradient_lwd = 1.) +
theme_ridges(grid = FALSE) +
scale_fill_gradient(low= "#8A8585", high= "#C2DAEF") +
theme(legend.position='none') + xlab("") + ylab("")
18. Area plot
누적값을 나타내는 영역 그래프 입니다.
ggplot(Group_Data) +
geom_area(aes(x= as.numeric(as.character(Year)), y = Mean , fill = Day ),alpha = 0.4) +
theme_classic() +
xlab("")
19. Polygon plot
그래프분포의 범위를 나타내는 그래프입니다. geom_polygon()이라는 명령어가 있지만, 해당 명령어는 쓰기가 조금 까다롭습니다. 요구하는 데이터 입력 방식이 간단하지가 않습니다. 그렇기 때문에 stat_ellipse()명령어를 사용하여 polygon 플랏을 그리도록 하겠습니다. stat_ellipse()처럼 stat으로 시작하는 명령어는 옵션에 geom = ‘polygon’ 처럼 어떻게 그래프를 그릴 것인지 옵션을 주어야 합니다.
ggplot(STOCK) +
stat_ellipse(geom = 'polygon',
aes(x = Volume, y = Stock.Trading, fill = Year), alpha = 0.2) +
geom_point(aes(x = Volume, y = Stock.Trading, col = Year),
alpha = 0.2) +
theme_classic() +
# 그래프 가시성을 위해 축 범위 조절
xlim(0,1000000) + ylim(0,50000000000) +
theme(axis.text.x = element_blank())
20. Rect plot
사각형 형태의 그래프입니다. 주로 waterfall그래프를 그리는데 활용이 됩니다.
ggplot(Group_Data) +
geom_rect(aes(xmin = as.numeric(as.character(Year)) - 0.5 ,
xmax = as.numeric(as.character(Year)) + 0.5,
ymin = Median, ymax = Max, fill = Year), alpha = 0.4) +
geom_hline(yintercept = mean(Group_Data$Median),
linetype = 'dashed', col = 'red') +
theme_classic() +
facet_wrap(~Day, nrow = 1) +
theme(axis.text.x = element_blank())
'MustLearning with R 1편' 카테고리의 다른 글
11. 기초통계이론 2단계 (0) | 2020.01.29 |
---|---|
10. 기초통계 이론 1단계 (1) | 2020.01.29 |
8. R 데이터 시각화 (0) | 2020.01.29 |
7. R 중급문법 3단계 (0) | 2020.01.29 |
6. R 중급문법 2단계 (0) | 2020.01.29 |