Back to posts Edit this post
Copy content

26 Apr 20:27

install.packages(c("httr2", "jsonlite", "dplyr", "purrr", "ggplot2", "patchwork")) library(httr2) library(jsonlite) library(dplyr) library(purrr) library(ggplot2) library(patchwork) # ------------------------------- # Ustaw swój klucz i współrzędne # ------------------------------- Sys.setenv(KACHELMANN_API_KEY = "KLUCZ") lat <- 52.4064 lon <- 16.9252 # ------------------------------- # Pobranie danych z działającego endpointa # ------------------------------- url <- paste0( "https://api.kachelmannwetter.com/v02/forecast/", lat, "/", lon, "/3day?units=metric" ) resp <- request(url) |> req_headers( Accept = "application/json", `X-API-Key` = Sys.getenv("KACHELMANN_API_KEY") ) |> req_error(is_error = function(resp) FALSE) |> req_perform() if (resp_status(resp) != 200) { cat(resp_body_string(resp), "\n") stop("API zwróciło błąd.") } raw <- resp_body_json(resp, simplifyVector = FALSE) # ------------------------------- # Funkcja pomocnicza # ------------------------------- pick_value <- function(x, candidates, default = NA) { for (nm in candidates) { if (!is.null(x[[nm]]) && length(x[[nm]]) > 0) { return(x[[nm]]) } } default } # ------------------------------- # 1 dzień -> 4 pory dnia # ------------------------------- day1 <- raw$data[[1]] parts_order <- c("night", "morning", "afternoon", "evening") parts_label <- c( night = "Noc", morning = "Rano", afternoon = "Popołudnie", evening = "Wieczór" ) meteo_1d <- map_dfr(parts_order, function(p) { x <- day1$timeOfDay[[p]] tibble( part = factor(parts_label[[p]], levels = unname(parts_label)), temp = as.numeric(pick_value(x, c("temp", "temperature", "tempAvg", "tempMax", "tempMin"))), wind = as.numeric(pick_value(x, c("windSpeed", "windspeed"))), gust = as.numeric(pick_value(x, c("windGust", "gust"))), precip = as.numeric(pick_value(x, c("precCurrent", "precip", "precipitation"), 0)), precip_prob = as.numeric(pick_value(x, c("precProb"), NA)), cloud = as.numeric(pick_value(x, c("cloudCoverage"), NA)) ) }) print(meteo_1d) # ------------------------------- # Meteogram - 3 panele # ------------------------------- p1 <- ggplot(meteo_1d, aes(part, temp, group = 1)) + geom_line(linewidth = 1) + geom_point(size = 2) + labs( title = paste0("Meteogram - ", day1$dateTime), subtitle = paste("lat:", raw$lat, "lon:", raw$lon), x = NULL, y = "Temperatura [°C]" ) + theme_minimal(base_size = 13) p2 <- ggplot(meteo_1d, aes(part, precip_prob)) + geom_col() + labs( x = NULL, y = "Prawdopodobieństwo opadu [%]" ) + theme_minimal(base_size = 13) p3 <- ggplot(meteo_1d, aes(part, wind, group = 1)) + geom_line(linewidth = 1) + geom_point(size = 2) + geom_line(aes(y = gust, group = 1), linetype = "dashed") + geom_point(aes(y = gust), shape = 1, size = 2) + labs( x = NULL, y = "Wiatr / porywy [m/s]", caption = "linia ciągła = wiatr, linia przerywana = porywy" ) + theme_minimal(base_size = 13) p1 / p2 / p3

No files