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

[R] 호주 인구분포 - Are there any people?

by 미니티스틱 2024. 8. 26.

 
 
호주에서 데이터 분석가로 일하고 있는만큼, 호주의 인구분포를 R로 나타내보았다. 
사용된 패키지는 terra, giscoR, tidyverse 이다. 
 

#-------------------------------------
# 1. GHSL데이터 웹사이트에서 다운로드
#-------------------------------------

url <- "https://jeodpp.jrc.ec.europa.eu/ftp/jrc-opendata/GHSL/GHS_POP_GLOBE_R2023A/GHS_POP_E2025_GLOBE_R2023A_4326_30ss/V1-0/GHS_POP_E2025_GLOBE_R2023A_4326_30ss_V1_0.zip"
file_name <- "GHS_POP_E2025_GLOBE_R2023A_4326_30ss_V1_0.zip"

options(timeout = max(300, getOption("timeout")))
download.file(
  url = url,
  path = getwd(),
  destfile = file_name
)

#-------------------------------------
# 2. 다운로드 받은 데이터 R에 Load
#-------------------------------------

unzip(file_name)
raster_name <- gsub(".zip", ".tif",file_name)

pop <- terra::rast(raster_name)

#-------------------------------------
# 3. giscoR에서 호주 국경 Load
#-------------------------------------

get_country_borders <- function(){
  country <- giscoR::gisco_get_countries(
    country = "AU",
    resolution = "3"
  )
  return(country)
}

country <- get_country_borders()


#----------------------------------------
# 5. GHSL데이터를 3에서 받은 호주 국경으로 Crop
#----------------------------------------

australia_pop <- terra::crop(
  pop,
  terra::vect(country),
  snap = "in",
  mask = T
)


#-------------------------------------
# 5. RASTER 데이터를 DATAFRAME으로 변환
#-------------------------------------

australia_pop_df <- as.data.frame(australia_pop, xy = T, na.rm = T)
head(australia_pop_df)


# 5-1. 카테고리 분류
#-------------------------------------
names(australia_pop_df)[3] <- "val"
australia_pop_df <- australia_pop_df |>
  dplyr::mutate(
    cat = dplyr::if_else(
      val > 0, "Yes", "No"
    )
  )

australia_pop_df$cat <- as.factor(
  australia_pop_df$cat
)

#-------------------------------------
# 6. MAP
#-------------------------------------

cols <- c("#0a1c29", "#edc241")

p <- ggplot() +
  geom_raster(
    data = australia_pop_df,
    aes(x = x,
        y = y,
        fill = cat
    )
  ) +
  scale_fill_manual(
    name = "Are there any people?",
    values = cols,
    na.value = "#0a1c29"
  ) +
  guides(
    fill = guide_legend(
      direction = "horizontal",
      keyheight = unit(5, "mm"),
      keywidth = unit(15, "mm"),
      label.position = "bottom",
      label.hjust = .5,
      nrow = 1,
      byrow = T
    )
  ) +
  theme_void() +
  theme(
    legend.position = "top",
    legend.title = element_text(size = 16, color = "grey10"),
    legend.text = element_text(size = 14, color = "grey10"),
    plot.caption = element_text(size = 10, color = "grey10", hjust = .25, vjust = 20),
    plot.margin = unit(c(t = 0, b = -1,
                          l = -1, r = -1), "lines")
  ) +
  labs(
    title = "",
    caption = "Data: Global Human Settlement Layer at 30 arcsec"
  )

p
반응형

댓글