지난번과 동일하게 오늘 사용할 데이터는 palmerpenguin::penguins
library(palmerpenguins)
library(tidyverse)
시작 전 데이터 훑어보기
str(penguins) %>% head(n=8)
## tibble [344 x 8] (S3: tbl_df/tbl/data.frame)
## $ species : Factor w/ 3 levels "Adelie","Chinstrap",..: 1 1 1 1 1 1 1 1 1 1 ...
## $ island : Factor w/ 3 levels "Biscoe","Dream",..: 3 3 3 3 3 3 3 3 3 3 ...
## $ bill_length_mm : num [1:344] 39.1 39.5 40.3 NA 36.7 39.3 38.9 39.2 34.1 42 ...
## $ bill_depth_mm : num [1:344] 18.7 17.4 18 NA 19.3 20.6 17.8 19.6 18.1 20.2 ...
## $ flipper_length_mm: int [1:344] 181 186 195 NA 193 190 181 195 193 190 ...
## $ body_mass_g : int [1:344] 3750 3800 3250 NA 3450 3650 3625 4675 3475 4250 ...
## $ sex : Factor w/ 2 levels "female","male": 2 1 1 NA 1 2 1 2 NA NA ...
## $ year : int [1:344] 2007 2007 2007 2007 2007 2007 2007 2007 2007 2007 ...
## NULL
Shape, Size, Alpha in Layer
shape = 21의 경우 안이 채워지지 않은 원 모양. 따라서 color를 적용하면 테두리 색을 바꾸는 것이고, fill을 해야 원 안쪽을 채우는 것.
즉 shape에 따라서 fill과 color를 조합할 줄 알아야 함.
penguins %>%
ggplot(aes(x = bill_length_mm, y = bill_depth_mm, fill = sex, color = island)) +
geom_point(shape = 21, size = 3, alpha = 0.5)
## Warning: Removed 2 rows containing missing values (geom_point).

penguins %>%
ggplot(aes(x = bill_length_mm, y = bill_depth_mm, fill = sex, color = island)) +
geom_point(shape = 21, size = 3, alpha = 0.5)
## Warning: Removed 2 rows containing missing values (geom_point).

geom_smooth() 갖고 놀기
먼저 geom_line을 그냥 적어보자
penguins %>%
filter(!is.na(sex)) %>%
ggplot(aes(x = bill_length_mm, y = bill_depth_mm, fill = sex, color = sex)) +
geom_point(shape = 21, size = 3, alpha = 0.5) +
geom_line()

각 집단별로 trend line을 그리고 싶어질 것이다. 그렇다면? geom_smooth()
penguins %>%
filter(!is.na(sex)) %>%
ggplot(aes(x = bill_length_mm, y = bill_depth_mm, fill = sex, color = sex)) +
geom_point(shape = 21, size = 3, alpha = 0.5) +
geom_smooth()
## `geom_smooth()` using method = 'loess' and formula 'y ~ x'

linear line으로 보고 싶다면? method = “lm”
penguins %>%
filter(!is.na(sex)) %>%
ggplot(aes(x = bill_length_mm, y = bill_depth_mm, fill = sex, color = sex)) +
geom_point(shape = 21, size = 3, alpha = 0.5) +
geom_smooth(method = "lm")
## `geom_smooth()` using formula 'y ~ x'

Line의 색, 굵기, 종류, 크기, 신뢰구간 표시여부를 바꾸고 싶다면?
penguins %>%
filter(!is.na(sex)) %>%
ggplot(aes(x = bill_length_mm, y = bill_depth_mm, fill = sex, color = sex)) +
geom_point(shape = 21, size = 3, alpha = 0.5) +
geom_smooth(method = "lm", color = "grey20", lty = 2, size = 2, se = F)
## `geom_smooth()` using formula 'y ~ x'

line by group이 아니라 전체 데이터를 대표하는 1개의 Line만 보고 싶다면?
color, fill을 최초 ggplot에서 설정하지 않고, geom_point()에서 aes() 설정하면 됨!
penguins %>%
filter(!is.na(sex)) %>%
ggplot(aes(x = bill_length_mm, y = bill_depth_mm)) +
geom_point(aes(fill = sex, color = sex), shape = 21, size = 3, alpha = 0.5) +
geom_smooth(method = "lm", col = "grey30", lty = 4)
## `geom_smooth()` using formula 'y ~ x'
