R | ggplot2 | bar chart

2023. 1. 3. 16:35·R/ggplot2

 

 

ggplot2 패키지를 사용하여 bar chart 막대그래프 그리는 방법

막대그래프는 주로 숫자형 변수와 범주형 변수의 관계를 볼 때 사용됨.

 

  1. X축의 값만 지정하여 그리는 방법(하나의 이산형 변수 사용)
  2. X축 1개 Y축 1개 각각 지정하여 그리는 방법(하나의 이산형 변수, 하나의 범주형 변수)

 

·ggplot2 패키지에는 총 3가지 함수 제공 geom_bar() , geom_col() , stat_count() 

geom_bar(
  mapping = NULL,
  data = NULL,
  stat = "count",
  position = "stack",
  ...,
  just = 0.5,
  width = NULL,
  na.rm = FALSE,
  orientation = NA,
  show.legend = NA,
  inherit.aes = TRUE
)

geom_col(
  mapping = NULL,
  data = NULL,
  position = "stack",
  ...,
  just = 0.5,
  width = NULL,
  na.rm = FALSE,
  show.legend = NA,
  inherit.aes = TRUE
)

stat_count(
  mapping = NULL,
  data = NULL,
  geom = "bar",
  position = "stack",
  ...,
  width = NULL,
  na.rm = FALSE,
  orientation = NA,
  show.legend = NA,
  inherit.aes = TRUE
)

 


 

00. 패키지 로드 및 데이터 불러오기 

- 데이터는 ggplot2 패키지 데이터 셋인 'diamonds' 사용 

library(ggplot2) # 패키지 로드

df <- diamonds
df %>% str()
df %>% head()

 

 

 

 


 

01. X축 변수만 지정하여 그래프 그리기 

 

1) 하나의 이산형 변수를 X축으로 지정

ggplot(diamonds) +
  geom_bar(aes(x = cut, fill = ..count..)) +
  xlab("") + ylab("") +
  scale_fill_gradient(low = "#CCE5FF", high =  "#FF00FF") +
  theme_classic() + 
  ggtitle("Continuous Color")

 

- stat='count'가 geom_bar의 default이기 때문에 y축에 자동으로 cut의 범주별로 count가 나타난다. 

 

ggplot(diamonds) +
  geom_bar(aes(x = cut, fill = cut), alpha = 0.4) +
  xlab("") + ylab("") +
  theme_classic() + 
  ggtitle("Discrete Color")

 

 

2) 하나의 이산형 변수를 y축으로 지정하여 plotting

# x축 대신 y축에 cut 변수를 넣어주면 됨
ggplot(diamonds) +
  geom_bar(aes(y = cut, fill = cut),alpha = 0.4) +
  xlab("") + ylab("") +
  theme_classic() + ggtitle("Discrete Color")

 

 

3) position = 'dodge' 사용 

- x축에 diamond의 color 변수를 지정하고 color에 따른 cut의 등급 count를 position = 'dodge'를 사용하여 plotting 할 수 있음.

ggplot(diamonds) +
  geom_bar(aes(x = color, fill = cut),
           position = 'dodge', alpha = 0.4) +
  xlab("") + ylab("") +
  theme_classic() + ggtitle("Discrete Color")

 

 

4) color별로 cut의 상대적인 비율을 나타내는 Bar Chart

 

·  x축 color

·  fill = cut

·  position = 'fill'

 

ggplot(diamonds)+
  geom_bar(aes(color, fill=cut), position='fill' , alpha = 0.4) +
  xlab("") + ylab("") +
  theme_classic() + ggtitle("다이아몬드의 color별로 cut의 비율")

 

 


 

02. X축 변수, Y축 변수 모두 지정하여 그래프 그리기 

·x축 변수, y축 변수 모두 지정하여 그래프를 그리기 위해선 꼭 stat = 'identity'를 넣어야 함!

 

1) cut에 따른 평균 Price Bar chart

 

· diamonds 데이터 셋 사용 

· cut별로 평균 price 계산

cut_mean <- diamonds %>% group_by(cut) %>% summarise(Mean = round(mean(price, na.rm = T)))

 

 

· x축을 cut 변수, y축을 Mean 변수로 지정하여 plotting

· 각 막대는 cut에 따라 색 지정(fill  = cut)

ggplot(cut_mean) +
  geom_bar(aes(x = cut, y = Mean, fill = cut), stat = 'identity', alpha = 0.4) +
  xlab("") + ylab("") +
  theme_classic() + ggtitle("Cut에 따른 평균 Price")

 

 

2) 환자(ID) 별로 수면시간 증가량(extra) 비교 Bar Chart

 

· sleep 데이터 셋 사용 

  - extra : 수면시간 증감량

  - group : 약의 종류 '1', '2'

  - ID: 환자 id

 

 

· x축 ID, y축 extra, fill = extra를 사용해 환자별로 복용한 약에 따른 수면시간의 증감을 bar chart로 그릴 수 있음

ggplot(sleep) +
  geom_bar(aes(x = ID, y = extra, fill = group),
           stat = 'identity',alpha = 0.4) +
  xlab("") + ylab("") +
  theme_classic() + ggtitle("약의 종류에 따른 환자의 수면시간 증감량")

 

 

· 다른 방법으로 x축 ID, y축 extra, fill = group , position = 'dodge'를 사용해 환자별로 복용한 약에 따른 수면시간의 증감을 bar chart로 그릴 수 있음

ggplot(sleep) +
  geom_bar(aes(x = ID, y = extra, fill = group),
           position = 'dodge',
           stat = 'identity',alpha = 0.4) +
  xlab("") + ylab("") +
  theme_classic() + ggtitle("약의 종류에 따른 환자의 수면시간 증감량")

 

 

 

3)  facet_wrap() 함수를 추가하여 여러 개의 그래프를 한 번에 그리기

ggplot(sleep) +
  geom_bar(aes(x = ID, y = extra, fill = group),
           position = 'dodge',
           stat = 'identity',alpha = 0.4) +
  facet_wrap(~group)+
  xlab("") + ylab("") +
  theme_gray() + ggtitle("약의 종류에 따른 환자의 수면시간 증감량")

 


참고 문헌(reference)

더보기

참고 서적 / 위키북스|Must Learning with R (개정판)

https://wikidocs.net/book/4315

 

Must Learning with R (개정판)

MustLearning with R 개정판입니다. 기존 제작한 책에서 다시 만들려고 했으나, 책의 구성이 어느정도 바뀐 부분도 있기 때문에 다시 새롭게 구성을 하였습…

wikidocs.net

 

참고 사이트 

https://ggplot2.tidyverse.org/reference/geom_bar.html

 

Bar charts — geom_bar

There are two types of bar charts: geom_bar() and geom_col(). geom_bar() makes the height of the bar proportional to the number of cases in each group (or if the weight aesthetic is supplied, the sum of the weights). If you want the heights of the bars to

ggplot2.tidyverse.org

https://m.blog.naver.com/PostView.nhn?blogId=coder1252&logNo=220931268317&proxyReferer=https:%2F%2Fwww.google.com%2F 

 

R - ggplot2 - Bar 그래프 그리기

bar 그래프는 아래와 같이 우리가 익숙히 알고 있는 막대그래프 입니다.  이번 포스팅에서는 ggplot2 ...

blog.naver.com

 

 

'R > ggplot2' 카테고리의 다른 글

R | ggplot2 | Line Plot  (0) 2023.01.18
R | ggplot2 | Scatter Plot(산점도)  (0) 2023.01.17
R | ggplot2 | Boxplot  (0) 2023.01.16
R | ggplot2 | Density Plot (밀도 플롯)  (0) 2023.01.16
R | ggplot2 | Histogram  (0) 2023.01.10
'R/ggplot2' 카테고리의 다른 글
  • R | ggplot2 | Scatter Plot(산점도)
  • R | ggplot2 | Boxplot
  • R | ggplot2 | Density Plot (밀도 플롯)
  • R | ggplot2 | Histogram
갬보리
갬보리
제발 코드정리좀 하자 (R, SQL, SAS, Python , etc...)
  • 갬보리
    보딩코
    갬보리
  • 전체
    오늘
    어제
    • 분류 전체보기 (49)
      • R (32)
        • dplyr (7)
        • preprocessing (2)
        • EDA (0)
        • ggplot2 (10)
        • plotly (11)
        • leaflet (2)
      • SQL (15)
      • SAS (0)
      • Python (1)
        • preprocessing (0)
        • ML (0)
        • Library (0)
      • ETC (1)
  • hELLO· Designed By정상우.v4.10.3
갬보리
R | ggplot2 | bar chart
상단으로

티스토리툴바