본문 바로가기
통계 & 데이터분석/DataViz

ggplot2 scatterplot 기초

by 미니티스틱 2023. 5. 26.

1.  DATA

CPS85: R의 mosaicData pacakage에 있는 CPS85데이터를 사용합니다. CPS는 The Current Population Survey의 약자로, 인구 조사(census)를 하는 기간 사이에 정보를 보완하는 데 사용됩니다. 이 데이터는 성별, 교육 기간, 경력 기간, 직업 상태, 거주 지역 및 조합원 자격을 포함하여 근로자의 임금 및 기타 특성에 대한 정보와 함께 무작위 표본으로 구성됩니다.

 

 

2.  Exploratory Analysis

시각화 전 Exploratory analysis는 필수.

# load data
data(CPS85 , package = "mosaicData")

# basic ggplot
ggplot(data = CPS85,
       mapping = aes(x = exper, y = wage)) +
  geom_point()

outlier detected

 

summary와 함께 히스토그램을 보면 wage에 아웃라이어가 있음을 알 수 있습니다. 아웃라이어를 제거 후, 다시 scatterplot을 그려보겠습니다.

outlier 제거 후

3. facet_wrap을 이용한 ggplot

아웃라이어를 제거 후, ggplot을 이용하여 데이터를 요리조리 시각화해보겠습니다(fun begins!)

ggplot(df, mapping = aes(x = exper, y = wage, color = sex)) + # base and define colour by group (shape, size, fill etc availabe)
  geom_point(alpha = .7, #transparency
             size = 3) + #point size
  geom_smooth(method = "lm", se=FALSE) + #overlay smoothing line "lm", "glm", "gam", "loess" or a function
  scale_x_continuous(breaks = seq(0,60,10)) + # x-axis scale
  scale_y_continuous(breaks = seq(0,30,10),label = scales::dollar) + # y-axis scale
  scale_color_manual(values = c("indianred1", "deepskyblue1")) + # manually pick the colours
  facet_wrap(~sector)+ # grouping view (categorical value)
  labs(title = "Relationship between experience & wage",   # labels 
       subtitle="by race",
      x = "Years of experience",
      y= "Wage per hour") +
  theme_classic() # theme

 

categorical value를 이용하여 그룹간 비교

 

왼쪽에서는 경력에 따른 남녀 임금의 차이를 직업군별로 볼 수 있고, 오른쪽에서는 인종(백인 vs 백인 외)별로 볼 수 있습니다. 분석하고자하는 목적에 따라, facet_wrap에 해당 catgorical variable을 넣어줍니다.

 

 

4.  facet_grid을 이용한 ggplot

facet_wrap에서는 하나의 categorical variable을 정하여 그에 따른 기존 플랏을 보여주는 것이었다면, facet_grid는 두개의 categorical variables을 이용하여 관계를 알아볼 수 있습니다.

 

ggplot(df, mapping = aes(x = exper, y = wage, color = sex)) +
  geom_point(alpha = .7,
             size = 3) +
  geom_smooth(method = "lm", se=FALSE) +
  scale_x_continuous(breaks = seq(0,60,10)) + 
  scale_y_continuous(breaks = seq(0,30,10),label = scales::dollar) +
  scale_color_manual(values = c("indianred1", "deepskyblue1")) + 
  facet_grid(sector~race)+
  labs(title = "Relationship between experience & wage",
       subtitle="by sector and race",
      x = "Years of experience",
      y= "Wage per hour")+
  theme_classic()

 

 

 

 

 

5.  ggplot 색 종류

ggplot이 알아서 색을 정해주기도 하지만, 위의 코드에서도 보았듯 scale_color_manual을 사용하여 이름으로 지정할 수도 있고, hex color기호로 사용할 수도 있습니다. 개인적으로는 이름을 사용하는 것이 더 편하여 리스트를 만들어보았습니다.(이름을 보는 재미가 꽤 쏠쏠합니다!) 무려 657가지 종류가 있습니다.

 

ggplot colour 종류

반응형

댓글