For geospatial applications, it may be convenient to convert isolines and isobands into simple features. This can be done with the function iso_to_sfg(), which converts an isolines or isobands object into an sf geometry collection. This converted object can then be further processed with functions from the sf package. For example, we can add them to an sf data frame and plot with ggplot2.
library(isoband)
library(ggplot2)
suppressWarnings(library(sf))
#> Linking to GEOS 3.8.1, GDAL 3.1.1, PROJ 6.3.1
m <- volcano
# make isobands
b <- isobands((1:ncol(m))/(ncol(m)+1), (nrow(m):1)/(nrow(m)+1), m, 10*(9:19), 10*(10:20))
bands <- iso_to_sfg(b)
data_bands <- st_sf(
level = 1:length(bands),
geometry = st_sfc(bands)
)
# make isolines
l <- isolines((1:ncol(m))/(ncol(m)+1), (nrow(m):1)/(nrow(m)+1), m, 10*(10:19))
lines <- iso_to_sfg(l)
data_lines <- st_sf(
level = 2:(length(lines)+1),
geometry = st_sfc(lines)
)
# plot with geom_sf()
ggplot() +
geom_sf(data = data_bands, aes(fill = level), color = NA, alpha = 0.7) +
geom_sf(data = data_lines, color = "black") +
scale_fill_viridis_c(guide = "none") +
coord_sf(expand = FALSE)As a second application of this feature, we will take a photograph and convert it into a set of polygons that we plot with false colors.
suppressMessages(library(magick))
# helper function to convert a raster image into isobands
sf_from_image <- function(image) {
image_gray <- image %>% image_quantize(colorspace = "gray")
image_raster <- as.raster(image_gray)
d <- dim(image_raster)
m <- matrix(c((255-col2rgb(image_raster)[1,])), nrow = d[1], ncol = d[2], byrow = TRUE)
b <- isobands(1:d[2], d[1]:1, m, 20*(0:13), 20*(1:14))
bands <- iso_to_sfg(b)
data <- st_sf(
level = letters[1:length(bands)],
geometry = st_sfc(bands)
)
}
# load the image, convert, and plot
img <- image_resize(image_read(system.file("extdata", "ocean-cat.jpg", package = "isoband")), "200x200")
img_sf <- sf_from_image(img)
ggplot(img_sf) +
geom_sf(color = "blue", fill = NA, size = 0.05) +
coord_sf(expand = FALSE) +
theme_gray() +
theme(
axis.ticks = element_blank(),
axis.text = element_blank(),
axis.title = element_blank(),
axis.ticks.length = grid::unit(0, "pt"),
plot.margin = margin(0, 0, 0, 0)
)