본문 바로가기
언어/R

[R-011] ggplot2 - geom_bar()

by 천왕지짐 2023. 5. 5.
가장 흔히 볼 수 있고 이해하기 쉬운 막대그래프에 대해서 알아보자.

 

막대 그래프를 사용하기 위해 ggplot2를 설치해야 되겠지만 tidyverse 패키지안에 ggplot2가 포함되어 있으므로 그냥 tidyverse를 설치했다면 library(tidyverse)만 해도 되겠다. 설치되어 있지 않다면 다음과 같이 설치하면 된다.

install.packages("tidyverse")
library(tidyverse)

데이터 셋은 diamonds를 앞에서 이미 본 사용하도록 하겠다. 

   - carat: 다이아몬드 무게
   - cut: 컷팅의 가치
   - color: 다이아몬스 색상
   - clarity: 깨끗한 정도
   - depth: 깊이 비율, z / mean(x, y)
   - table: 가장 넓은 부분의 너비 대비 다이아몬드 꼭대기의 너비
   - price: 가격
   - x: 길이
   - y: 너비
   - z: 깊이

 

일부만 표시해보면 다음과 같다.

ggplot2의 가장 간단한 사용법은 data, aes, 그래프 종류이다.

ggplot(data=diamonds, aes(x=cut)) +
           geom_bar()                                                 #축이 하나일 때는 geom_bar()를 두개일 때는 geom_col()을 사용한다.

데이터는 53,940건이다.

참고로, 축이 두개인 경우 geom_bar를 사용하려고 한다면 geom_bar(stat='identity')를 사용해야 한다.

geom_bar() 안에는 다양한 옵션을 포함시킬 수 있다. ?geom_bar로 확인해 보자.

 

 

가장 기본 그래프에 우리가 원하는 사항들을 추가해보자.

 

제일 먼저 다섯가지 종류의 커팅 가치에 대해 색상을 변경해 보자.

ggplot(data=diamonds, aes(x=cut)) +
           geom_bar(col = 'black',
                             fill = 'red') 

geom_bar에서 fill을 사용할 수도 있고 aes에서 fill을 사용할 수 있는데 aes에서 사용하는 것이 훨씬 유연하다. geom_bar에서는 색깔을 직접 지정하지만 aes에서는 열의 값에 따라 자동으로 색이 지정될 수 있도록 할 수 있다.

ggplot(data=diamonds, aes(x=cut, fill=cut)) +
           geom_bar(col = 'black') 

각각의 막대마다 원하는 색상을 부여하기 위해서는 다음과 같이 scale_fill_manual(values =c("","",...))을 사용한다.

ggplot(data=diamonds, aes(x=cut, fill = cut)) +
  geom_bar(col = 'black') +
  scale_fill_manual(values = c("red", "blue", "green", "yellow", "purple"))

각 막대에 해당 값이 표시되도록 해보자.

diamonds %>%
   count(cut) %>%
   ggplot(aes(x=cut, y=n, fill=cut)) +
   geom_bar(stat = "identity", col = 'black') +
   scale_fill_manual(values = c("red", "blue", "green", "yellow", "purple")) + 
   geom_text(aes(label = n), vjust = -0.5)                                                        #vjust가 포함되지 않으면 막대에 숫자가 겹친다.

막대가 가로로 표시되도록 해보자.

diamonds %>%
  count(cut) %>%
  ggplot(aes(x=n, y=cut, fill=cut)) +
  geom_bar(stat="identity", col='black') +
  scale_fill_manual(values = c("red", "blue", "green", "yellow", "purple")) +
  geom_text(aes(label=n), hjust=-0.1)

순서를 역순으로 바꿔보자.

diamonds %>%
  count(cut) %>%
  ggplot(aes(x=n, y=cut, fill=cut)) +
  geom_bar(stat="identity", col='black') +
  scale_fill_manual(values = c("red", "blue", "green", "yellow", "purple")) +
  geom_text(aes(label=n), hjust=-0.1) +
  scale_y_discrete(limits = rev(levels(diamonds$cut)))

제목과 x축, y축 이름도 변경해 보자.

diamonds %>%
  count(cut) %>%
  ggplot(aes(x=n, y=cut, fill=cut)) +
  geom_bar(stat="identity", col='black') +
  scale_fill_manual(values = c("red", "blue", "green", "yellow", "purple")) +
  geom_text(aes(label=n), hjust=-0.1) +
  scale_y_discrete(limits = rev(levels(diamonds$cut))) +
  labs(title = "Diamond Cuts", x = "Count", y = "Cut")

시간히 허락되면 ggplot 그래프 코드 작성을 자동으로 해주는 esquisse 패키지에 대해서 학습해보기 바란다.

패키지 설치하고 addins에서 'ggplot2' builder를 통해 사용

'언어 > R' 카테고리의 다른 글

통계량, boxplot, t검정  (0) 2023.05.22
[R-012] R - markdown  (0) 2023.05.14
[R-010] ggplot2 - geom_point()  (0) 2023.05.03
[R-009] 패키지 - 데이터 시각화  (0) 2023.04.16
[R-008] R패키지 - 데이터 핸들링(dplyr)  (0) 2023.04.15

댓글