1 날씨 보고서

1.1 데이터

library(httr)
library(glue)
library(jsonlite)
library(tidyverse)

KMA_KEY <- "S7wtSg%2B7m7gyL5mmBNmSPQXacADqMkzhwff8eIijjTax0bfltvPwB8wAPbMK7qMb75He%2FeWQ8ktL0WcnyGcapg%3D%3D"

code_table <- tribble(~"category", ~"항목명", ~"단위", 
                      "POP", "강수확률", "%",
                      "PTY", "강수형태", "코드값",
                      "R06", "6시간 강수량", "범주 (1 mm)",
                      "REH", "습도", "%",
                      "S06", "6시간 신적설", "범주(1 cm)",
                      "SKY", "하늘상태", "코드값",
                      "T3H", "3시간 기온", "℃",
                      "TMN", "아침 최저기온", "℃",
                      "TMX", "낮 최고기온", "℃",
                      "UUU", "풍속(동서성분)", "m/s",
                      "VVV", "풍속(남북성분)", "m/s",
                      "WAV", "파고", "M",
                      "VEC", "풍향", "m/s",
                      "WSD", "풍속", "1")


## 날짜 전처리
today_date <- Sys.Date() %>%  as.character() %>% 
  str_remove_all(pattern = "-")

## RESTful 호출
bundang_kma_url <- glue("http://apis.data.go.kr/1360000/VilageFcstInfoService/getVilageFcst?serviceKey={KMA_KEY}&numOfRows=10&pageNo=1&base_date={today_date}&base_time=0230&nx=62&ny=122&dataType=JSON")

bundang_resp <- GET(bundang_kma_url)

## JSON --> 데이터프레임 변환
bundang_list <- jsonlite::fromJSON(content(bundang_resp, "text"), simplifyVector = FALSE)

bundang_df <- data.frame(Reduce(rbind, bundang_list$response$body$items$item)) %>% 
  as_tibble() %>% 
  mutate_all(unlist)

## 데이터프레임 가독성 있게 표현
bundang_df <- bundang_df %>% 
  left_join(code_table, by="category") %>% 
  select(fcstDate, fcstTime, category, 항목명, fcstValue, 단위)

bundang_df
# A tibble: 10 x 6
   fcstDate fcstTime category 항목명         fcstValue 단위       
   <chr>    <chr>    <chr>    <chr>          <chr>     <chr>      
 1 20200913 0600     POP      강수확률       20        %          
 2 20200913 0600     PTY      강수형태       0         코드값     
 3 20200913 0600     R06      6시간 강수량   0         범주 (1 mm)
 4 20200913 0600     REH      습도           80        %          
 5 20200913 0600     S06      6시간 신적설   0         범주(1 cm) 
 6 20200913 0600     SKY      하늘상태       3         코드값     
 7 20200913 0600     T3H      3시간 기온     17        ℃          
 8 20200913 0600     TMN      아침 최저기온  17.0      ℃          
 9 20200913 0600     UUU      풍속(동서성분) 0         m/s        
10 20200913 0600     VEC      풍향           360       m/s        

1.2 시각화

plot_title <- glue::glue("성남시 분당구 동네예보 서비스: {unique(bundang_df$fcstDate)}, {unique(bundang_df$fcstTime)}")
                         
bundang_df %>% 
  mutate(fcstValue = as.numeric(fcstValue)) %>% 
  filter(항목명 %in% c("강수확률", "습도")) %>% 
  ggplot(aes(x=항목명, y=fcstValue, fill = 항목명)) +
    geom_col(width=0.5, show.legend = FALSE) +
    facet_wrap(~항목명, scales="free_x")  +
    labs(x="", y="확률(%)", title=plot_title)+
    theme_bw()

 

데이터 과학자 이광춘 저작

kwangchun.lee.7@gmail.com