Political Science Analysis

R을 이용한 대한민국 국회 의석수 시각화

r-code-for-data-analysis 2023. 6. 10. 13:28

아래 사이트를 들어가 보면 21대 대한민국 국회의원 의석수를 시각화가 잘 되어 있다. 

 

https://open.assembly.go.kr/portal/assm/assmPartyNegotiationPage.do

 

열린국회정보

국회를 열다, 정보를 나누다.

open.assembly.go.kr

 

R을 이용하여 이와 같은 정당별 의석수 시각화 예제가 있어 따라 해 보았다.

 

참고 자료 

https://rforpoliticalscience.com/2023/01/19/how-to-create-semi-circle-parliament-graphs-with-the-ggparliament-package-in-r/

 

How to create semi-circle parliament graphs with the ggparliament package in R

Packages we will need: library(tidyverse) library(forcats) library(ggparliament) Check out part 1 of this blog where you can follow along how to scrape the data that we will use in this blog. It wi…

rforpoliticalscience.com

 

우선 필요한 패키지는 "ggparliament"이다. 

R의 장점은 다양한 패키지가 이공계뿐 아니라 인문, 사회 계열에도 잘 개발되어 있다는 것이다. 

library(tidyverse)
library(magrittr)
library(forcats)
library(ggparliament)

 

https://github.com/zmeers/ggparliament

 

GitHub - zmeers/ggparliament: Simple parliament plots using ggplot2

Simple parliament plots using ggplot2. Contribute to zmeers/ggparliament development by creating an account on GitHub.

github.com

 

그럼 본격적으로 코딩을 해 보자

우선 위 대한민국 국회 의석수를 엑셀에 붙여 넣기 해 보자.

 

 

R에서 datapasta add in을 이용하여 tibble로 붙여 넣기 하면 간단히 변수화 할 수 있다. 

 

df <- tibble::tribble(
  ~정당,   ~계,
  "더불어민주당", 167L,
  "국민의힘", 113L,
  "정의당",   6L,
  "기본소득당",   1L,
  "시대전환",   1L,
  "진보당",   1L,
  "무소속",  10L
) %>% mutate(정당 = as.factor(정당))

 

그리고 난 후 소속 정당별 색을 지정하자. magrittr 패키지를 이용하면 %<>% 를 이용하여 바로 칼럼을 만들 수 있다. 

df %<>% 
  mutate(party_color = case_when(정당 == "기본소득당" ~ "#66bb66",
                                 정당 == "더불어민주당" ~ "#6699ff",
                                 정당 == "시대전환" ~ "#64532a",
                                 정당 == "국민의힘" ~ "#8e2420",
                                 정당 == "진보당" ~ "#1e2420",
                                 정당 == "무소속" ~ "#326760",
                                 정당 == "정의당" ~ "#ee9f27"))

 

다음은 ggparliament 패키지에 들어있는 함수를 사용해서 전처리 하자.

df_coord <- parliament_data(election_data = df,
                                 type = "semicircle", 
                                 parl_rows = 7,  
                                 party_seats = df$계)

 

마지막은 시각화

df_coord %>% 
  ggplot(aes(x = x,
             y = y,
             colour =정당)) +
  geom_parliament_seats(size = 10) +
  bbplot::bbc_style() + 
  ggtitle("대한민국 국회 정당별 의석수") +
  theme(text = element_text(size = 20),
        legend.title = element_blank(),
        axis.text.x = element_blank(),
        axis.text.y = element_blank()) +  
  scale_colour_manual(values = df_coord$party_color,
                      limits = df_coord$정당)

 

이렇게 하면 국회 사이트에서 보이는 것과 같은 그림이 그려진다. 

 

728x90
반응형