티스토리 뷰

ggplot 에서는 막대그래프를 그리는 여러가지 방법이 있다. geom_bar, geom_col, geom_histogram 이 있는데, 대부분 geom_col 을 가지고 처리하지만, 이번에는 geom_histogram 으로 그려보려 한다. 최종결과는 아래와 같은데, geom_col 로 만든거랑 별반 다르지 않다. 다만, 데이터를 굳이 group by 해서 집계를 하지 않아도 알아서 count 를 세어 빈도를 그래프로 자동으로 만들어주는 장점이 있다.

 

 

저번 포스팅에서도 언급한 rent 데이터셋을 그대로 이용하는데, 별도의 그룹핑 집계를 하지 않도록 한다.

 

ggplot2 막대그래프 만들기

아래와 같이 막대그래프를 만들어보고자 한다. 컨셉은, 가장 높은 막대에만 가장 진한색상으로 강조하고, 년도와 건수로 더 강조해본다. #tidytuesday 에서 데이터를 하나 가져와서 샘플로 사용한

emflant.tistory.com

rent <- readr::read_csv('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2022/2022-07-05/rent.csv')

rent_sanfrancisco1 = rent %>% filter(city == 'san francisco')

 

만들어진 데이터셋을 이용하는데 별 다른 셋팅없이도 히스토그램 그래프가 만들어진다. 여기서 주목할 것은 2개의 스크립트가 동일한 결과를 보여주는데, ..count.. 라는 변수로 자동계산되어서 y 축에 디폴트로 셋팅되는 구조이다. 그리고 히스토그램은 bins 와 binwidth 를 설정할 수 있는데, bins 는 막대 갯수를 직접 셋팅하는 것이고, binwidth 는 비율로 막대를 조정하는데, 1 로 하면 x 축의 값에 1:1 대응 되면서 표시되는 듯 하다. 2개를 동시에 셋팅할 수는 없고 둘중 하나만 적용되니 유의할 것.

ggplot(rent_sanfrancisco1) +
  geom_histogram(aes(year), binwidth = 1, show.legend = F) +
  theme_minimal()
  
ggplot(rent_sanfrancisco1) +
  geom_histogram(aes(x = year, y = ..count..), binwidth = 1, show.legend = F) +
  theme_minimal()

반응형

fill 변수를 이용해서 색을 입혀본다. 여기 추가한건 히스토그램이 바(bar)간에 간격이 딱 붙어 있다보니, 좀 떨어트리고 싶다면 color 를 힌색으로 하면 약간 떨어진 효과를 낼 수 있다.

ggplot(rent_sanfrancisco1) +
  geom_histogram(aes(year, fill = ..count..), binwidth = 1, show.legend = F, colour = "gray100") +
  scale_fill_gradient(low = "#9FE8FA", high = "#26BAEE" ) +
  theme_minimal()

 

어디선가 자세한 설명문서를 찾은 건 아니지만, 밀도를 기반으로 히스토그램을 만들수도 있는데, 아래와 같이 ..density.. 변수를 이용하면 된다. 잘 보면, y 축값이 아까와 달리 1 미만의 수로 바뀐걸 알 수 있다.

ggplot(rent_sanfrancisco1) +
  geom_histogram(aes(year, y = ..density.., fill = ..density..), binwidth = 1, show.legend = F) +
  scale_fill_gradient(low = "#9FE8FA", high = "#26BAEE" ) +
  theme_minimal()

 

 

최종결과물이다. 맘에 드는 색상 찾는게 항상 일인거 같다.

ggplot(rent_sanfrancisco1) +
  geom_histogram(aes(year, fill = ..count..), 
                 binwidth = 1, show.legend = F) +
  scale_fill_gradient(low = "#C4DFAA", high = "#73A9AD" ) +
  scale_x_continuous(breaks = c(2000, 2004, 2018)) +
  theme_void(base_family = "AppleSDGothicNeo-ExtraBold", base_size = 13) +
  theme(
    legend.position = "none",
    axis.text.x = element_text(margin = margin(0.2,0,0,0,"cm"), size = 10),
    plot.margin = margin(0.5,1,1,1,"cm")
  )

 

마지막으로, patchwork 라이브러리를 통해서 여러개를 합쳐서 만들었다. binwidth 를 조정하면서 히스토그램의 이미지가 어떻게 변화하는지 볼 수 있다. stat_bin 을 이용해서 가장 높은 바(bar)위에 값을 추가했다.

ggplot(rent_sanfrancisco1) +
  geom_histogram(aes(year, fill = ..count..), 
                 binwidth = 5,
                 show.legend = F) +
  stat_bin(geom = "text", aes(year, label = ifelse(..count.. == max(..count..), 
                                                   formatC(..count.., format="f", big.mark=",", digits = 0), "")),
           binwidth = 5, colour = "gray30", vjust = -0.5,
           family = "AppleSDGothicNeo-ExtraBold", size = 6) +
  scale_fill_gradient(low = "#C4DFAA", high = "#73A9AD" ) +
  scale_y_continuous(expand = expansion(c(0, 0.25))) +
  labs(title = paste0("* binwidth = ",in_binwidth)) +
  theme_void(base_family = "AppleSDGothicNeo-ExtraBold", base_size = 12) +
  theme(
    legend.position = "none",
    axis.text.x = element_text(margin = margin(0.2,0,0,0,"cm"), size = 12, colour = "gray30"),
    plot.margin = margin(1,1,1,1,"cm")
  )
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함