220826 Day4

유예지·2022년 8월 26일

ggplot2 : 그래픽 패키지 (시각화)

4. 라벨 : + labs(title='', x='', y='')

-그래프의 제목과, x축과 y축에 이름을 지정해줄 수 있다

library(ggplot2)

ggplot(mpg, aes(x=displ, y=hwy, color=drv)) +
  geom_point(size = 2) + geom_smooth(method="lm")

install.packages("ggthemes")
library(ggthemes)   #theme_economist()를 실행하기 위함

ggplot(mpg, aes(x=displ, y=hwy)) +
  geom_point(size = 2, aes(color=drv)) + theme_economist()
             
g <- ggplot(mpg, aes(x=displ, y=hwy)) +
  geom_point(size = 2, aes(color=drv))             

g + theme_economist() + 
  labs(title="배기량 연비 비교", x="배기량", y="연비")

g + theme_economist() + 
  labs(title="배기량 연비 비교") + xlab("배기량")  #x축에만 이름 지정

5. 패싯 : facet_grid(drv ~ cut); 쪼개서 나타냄

g <- ggplot(mpg, aes(x=displ, y=hwy)) +
  geom_point(size = 2, aes(color=drv, shape=drv))
g  #drv 때문에 색깔과 모양이 각각 3가지씩으로 표현된다

g + facet_grid(drv ~ .)  #drv로 행 분리
g + facet_grid(. ~ drv)  #drv로 열 분리
g + facet_grid(drv ~ cyl)  #drv로 행과 열 모두 분리

* facet_wrap( ~ ____)

-행 또는 열의 개수가 많아지면 warp()을 이용한다

p <- ggplot(mpg, aes(displ, hwy)) + geom_point()
p
p + facet_wrap(vars(class))

mpg$class
unique(mpg$class)

p + facet_wrap( ~ class)  #class에 따라서 - 7개로 나뉨
p + facet_wrap( ~ drv)    #drv에 따라서 - 3개로 나뉨

g + facet_wrap( ~ class)  
g + facet_wrap( ~ drv)

g + facet_wrap( ~ class, nrow = 4)  #행의 개수 = 4
g

* geom_jitter() : 겹쳐있는 데이터 값을 흐트러뜨려서 보여줌

ggplot(mpg, aes(x=displ, y=hwy)) +
  geom_point(size = 2, aes(color=drv))
  
mpg
ggplot(mpg, aes(x=displ, y=hwy, color=drv)) +
  geom_point(size = 2, position = 'jitter')

ggplot(mpg, aes(x=displ, y=hwy, color=drv)) +
  geom_point(size = 2) + geom_jitter()

ggplot(mpg, aes(x=displ, y=hwy, color=drv)) +
  geom_point(size = 2) +
  geom_jitter(width = 0.5, height = 0.5)

* geom_line()

ggplot(mpg, aes(x=displ, y=hwy, color=drv)) +
  geom_point(size=0.5) + geom_line(size=.5)

* geom_bar()

mpg$displ
summary(mpg$displ)
str(mpg)

ggplot(mpg, aes(x=displ)) + geom_bar()  #displ은 num(dbl)-연속적

ggplot(mpg, aes(x=drv)) + geom_bar()  #drv는 chr

ggplot(mpg, aes(x=year)) + geom_bar()  #year는 int

mpg$year <- as.character(mpg$year)  #year의 데이터 형태 변경
ggplot(mpg, aes(x=year)) + geom_bar()

mpg$year <- as.factor(mpg$year)
str(mpg)  #year의 factor는 2 levels(1999, 2008)라는 것을 확인할 수 있다
mpg$year <- as.integer(mpg$year)

ggplot(mpg, aes(x=class)) + geom_bar()  #x축 하나만 지정했고, class는 chr

ggplot(mpg, aes(x=class)) + 
  geom_bar(color='blue', fill='skyblue')

ggplot(mpg, aes(x=class, fill=displ)) + 
  geom_bar()  #aes안에 넣을 때는 color나 fill을 '칼럼명'으로 지정, displ은 num(dbl)이어서 색이 나오지 않는다

ggplot(mpg, aes(x=class, fill=drv)) + 
  geom_bar()  #drv는 chr, 3가지 값이 있어 3가지의 색으로 나타난다

* position =

ggplot(mpg, aes(x=displ)) + geom_bar()

ggplot(mpg, aes(x=displ, fill=drv)) + geom_bar()
ggplot(mpg, aes(x=displ, fill=factor(drv))) + geom_bar()
#factor() : 데이터를 나타낼때만 순간적으로 변형이 필요할 때

ggplot(mpg, aes(x=class, fill=drv)) + 
  geom_bar(position = 'dodge')  #dodge : 겹치지 않고 펼쳐서 본다

ggplot(mpg, aes(x=class, fill=class)) + 
  geom_bar(position = 'dodge')

ggplot(mpg, aes(x=drv, fill=class)) + 
  geom_bar(position = 'dodge')

ggplot(mpg, aes(x=class, fill=drv)) + 
  geom_bar(position = 'fill')

ggplot(mpg, aes(x=class, fill=factor(drv))) + 
  geom_bar(position = 'fill')

* geom_histogram()

ggplot(mpg, aes(x=displ)) + geom_bar()

ggplot(mpg, aes(x=displ)) + geom_histogram()
#histogram - 연속적, bar - 불연속적

ggplot(mpg, aes(x=class)) + geom_histogram(stat = 'count')
#class는 데이터 형태가 연속적이지 않기 때문에 histogram으로 나태내기 위해서는
연속적으로 만들어주는 절차(stat = 'count')가 필요하다

ggplot(mpg, aes(x=class)) + geom_bar()

* binwidth : 한 막대 그래프의 넓이 조절

-bin : 네모난 쓰레기통 모양을 의미
-bins : 막대 그래프의 개수

ggplot(mpg, aes(x=displ)) + geom_histogram(binwidth = 0.15)

ggplot(mpg, aes(x=displ)) + geom_histogram(bins = 10)

ggplot2 정리

1. colour, shape, size

* colour=

ggplot(mpg, aes(displ, hwy)) + geom_point()

ggplot(mpg, aes(displ, cty, colour=class)) + geom_point()

ggplot(mpg, aes(displ, hwy)) + geom_point(aes(colour = 'blue'))
ggplot(mpg, aes(displ, hwy)) + geom_point(colour = 'blue')


diamonds
str(diamonds)
ggplot(diamonds, aes(carat, price, colour=clarity)) + geom_point()
#데이터의 형태가 'Ord.factor'인 것만 color를 줄 수 있다

* colour= 대신에 shape= 으로

ggplot(diamonds, aes(carat, price, shape=clarity)) + geom_point()

* size=

-연속형 변수에 size= 를 하면 -> 데이터 값에 따라 점의 크기가 달라진다

ggplot(mpg, aes(displ, cty, size=cty)) + geom_point()

ggplot(mpg, aes(displ, cty, size=cty)) + geom_point(colour='red')
ggplot(mpg, aes(displ, cty, size=cty)) + geom_point(colour=cty)
ggplot(mpg, aes(displ, cty, size=cty)) + geom_point(aes(colour=cty))

ggplot(mpg, aes(displ, cty, size=cty, color=drv)) + geom_point()

2.

economics
ggplot(economics, aes(date, unemploy)) + geom_line()

ggplot(mpg, aes(cty, hwy)) + geom_boxplot()

ggplot(mpg, aes(cty, hwy)) + geom_point() + geom_smooth(method = 'lm')

ggplot(mpg, aes(cty, fill=drv)) + geom_histogram(bins = 20)

3. Facetting

ggplot(mpg, aes(displ, hwy)) + geom_point() + facet_wrap(~class)

4. geom_boxplot()

ggplot(mpg, aes(drv, hwy)) + geom_point()
#어느 한 변수가 categorical variables(범주형 변수)일 때 geom_point()를 쓰면 상자가 아닌 점 그림이 나온다

install.packages("dplyr")
library(dplyr)
library(ggplot2)
ggplot(mpg, aes(drv, hwy)) + geom_boxplot()

* hwy값의 이상치를 갖고 있는 제조사는?

mpg %>% select(manufacturer, drv, hwy) %>% filter(hwy < 20)  #내가 생각한 답
mpg %>% group_by(drv) %>% arrange(hwy)

* geom_violin()

ggplot(mpg, aes(drv, hwy)) + geom_violin()

* geom_jitter()

ggplot(mpg, aes(drv, hwy)) + geom_jitter()

5. geom_bar()

drugs <- data.frame(drug=c('a','b','c'), effect=c(4,9,6))
drugs  #간단한 형태의 표; 이 데이터가 가장 중요
ggplot(drugs,aes(x=drug, y=effect)) + geom_bar()  #변수가 2개
ggplot(drugs,aes(x=drug, y=effect)) + geom_bar(stat='identity')  #1차원 자료
ggplot(drugs,aes(x=drug, y=effect)) + geom_col()  #2차원 자료

6. geom_line()

economics  #economics에서의 data의 데이터형태는 date, 'date'자체로 인식하는 것

ggplot(economics, aes(date, uempmed)) + geom_line()

ggplot(economics, aes(date, unemploy / pop)) + geom_line()
#mutate()로 (unemploy / pop)에 대한 새 변수를 먼저 만들지 않아도 출력이 가능하다

7. 구동방식(drv)별로 도시주행(cty)의 평균을 막대 그래프로 나타내라.

mpg
ggplot(mpg, aes(drv, mean(cty))) + geom_bar()
ggplot(mpg, aes(drv, mean(cty))) + geom_bar(stat = 'identity')
ggplot(mpg, aes(drv, mean(cty))) + geom_col()

8. 제조사(manufacture)별로 구동방식(drv)에 따른 도시주행(cty)의 평균을 막대그래프로 나타내라.

#내가 생각한 답
mpg %>% group_by(manufacturer, drv) %>% summarise(mean(cty))
ggplot(mpg, aes(drv, mean(cty), fill=manufacturer)) + geom_col()

#선생님이 알려주신 내용
mpg %>% group_by(manufacturer, drv) %>% summarise(mean(cty))
df <- mpg %>% group_by(manufacturer, drv) %>% summarise(mean(cty))
ggplot(df, aes(manufacturer, `mean(cty)`, fill=drv)) + geom_col()
#`mean(cty)` != 'mean(cty)' 다른 따옴표 이다.
#`~~~` : backtick

mpg %>% group_by(manufacturer, drv) %>% summarise(mean(cty)) %>% 
  ggplot(aes(manufacturer, `mean(cty)`, fill=drv)) + geom_col()

mpg %>% group_by(manufacturer, drv) %>% summarise(평균=mean(cty)) %>% 
  ggplot(aes(manufacturer, 평균, fill=drv)) + geom_col()

0개의 댓글