본문 바로가기
R

[R] ggplot2: facet_wrap(집단별로 분할하여 시각화 하기)

by rubyda 2021. 9. 1.
728x90

 

head(taiwan_real_estate)

  dist_to_mrt_m n_convenience house_age_years price_twd_msq
1      84.87882            10        30 to 45     11.467474
2     306.59470             9        15 to 30     12.768533
3     561.98450             5         0 to 15     14.311649
4     561.98450             5         0 to 15     16.580938
5     390.56840             5         0 to 15     13.040847
6    2175.03000             3         0 to 15      9.712557

위 데이터는 대만 부동산 데이터이다. 연령대별로 price_twd_msq (주택 가격)을 시각화 하려고 한다.

 

# Using taiwan_real_estate, plot price_twd_msq
ggplot(taiwan_real_estate, aes(x = price_twd_msq)) +
  # Make it a histogram with 10 bins
  geom_histogram(bins = 10)

 

이때 하나의 그래프에서 연령대별로 주택가격을 분할하여 표현하고 싶다면 어떻게 해야할까??

 

facet_wrap 함수를 사용하면 된다.

# Using taiwan_real_estate, plot price_twd_msq
ggplot(taiwan_real_estate, aes(x = price_twd_msq)) +
  # Make it a histogram with 10 bins
  geom_histogram(bins = 10) +
  # Facet the plot so each house age group gets its own panel
  facet_wrap(vars(house_age_years))

짠!!