Skip to content

Instantly share code, notes, and snippets.

@dieghernan
Created November 14, 2022 11:03
Show Gist options
  • Save dieghernan/ef30e399d148988018381864dd67aca8 to your computer and use it in GitHub Desktop.
Save dieghernan/ef30e399d148988018381864dd67aca8 to your computer and use it in GitHub Desktop.
Raster with heaxgons
library(geodata)
library(giscoR)
library(tidyterra)
library(tidyverse)
library(terra)
library(sf)
folder <- ifelse(dir.exists("~/R/mapslib/misc"),
"~/R/mapslib/misc",
tempdir()
)
tmin <- worldclim_country("DEU", "tmin", path = folder) %>%
select(11)
names(tmin) <- "tmin"
plot(tmin)
library(giscoR)
cntry <- gisco_get_countries(country = "Germany", epsg = 3035)
# Transform crs
tmin2 <- project(tmin, pull_crs(cntry))
plot(tmin2)
# Create hexbins
adjustarea <- sqrt(2 * 100000 * 1000 / sqrt(3))
hex <- st_make_grid(cntry,
square = FALSE, flat_topped = TRUE,
cellsize = adjustarea
)
units::set_units(st_area(hex[1]), "km^2")
hex <- st_sf(id = seq_len(length(hex)), geom = hex)
# Cut by centroid
cents <- st_centroid(hex, of_largest_polygon = TRUE)
ids <- st_filter(cents, cntry)
# And select
hex_end <- hex %>% inner_join(ids %>% st_drop_geometry())
# Rasterize
hex_end$min <- exactextractr::exact_extract(tmin2, hex_end, "mean")
range(hex_end$min)
ggplot(hex_end) +
geom_sf(aes(fill = min)) +
scale_fill_whitebox_c(palette = "deep", direction = -1,
breaks = seq(-4, 6, 1)
) +
guides(fill = guide_legend(
title = " ºC.",
direction = "horizontal",
nrow = 1,
keywidth = 1.5,
keyheight = 0.5,
label.position = "bottom",
title.position = "right"
)) +
theme_minimal() +
theme(
# plot.background = element_rect("grey99", colour = NA),
plot.margin = margin(20, 20, 20, 20),
plot.title = element_text(face = "bold"),
plot.subtitle = element_text(
margin = margin(b = 10)
),
legend.position = "bottom",
legend.key = element_rect(fill = "red", colour = NA, linewidth = 0),
legend.spacing.x = unit(0, "pt")
) +
labs(
title = "Winter is coming to Germany",
subtitle = "Avg. Minimum Temperature in November (25 km2 cell).",
caption = "Source: WordClim"
)
ggsave("deu.png", scale = 1.5, bg = "white")
knitr::plot_crop("deu.png")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment