I would like to insert the colors in the second map that uses the tmap
function, as I did using the first code.
First code
library(terra)
library(geodata)
library(raster)
brz <- geodata::gadm("Brazil", level=2, path=".")
mun <- brz[brz$NAME_2 == "Castro", ]
pdata <- data.frame(Latitude = c(-24.781624, -24.775017, -24.769196, -24.761741, -24.752019, -24.748008, -24.737312, -24.744718, -24.751996, -24.724589, -24.8004, -24.796899, -24.795041, -24.780501, -24.763376, -24.801715, -24.728005, -24.737845, -24.743485, -24.742601, -24.766422, -24.767525, -24.775631, -24.792703, -24.790994, -24.787275, -24.795902, -24.785587, -24.787558, -24.799524),
Longitude = c(-49.937369, -49.950576, -49.927608, -49.92762, -49.920608, -49.927707, -49.922095, -49.915438, -49.910843, -49.899478, -49.901775, -49.89364, -49.925657, -49.893193, -49.94081, -49.911967, -49.893358, -49.903904, -49.906435, -49.927951, -49.939603, -49.941541, -49.94455, -49.929797, -49.92141, -49.915141, -49.91042, -49.904772, -49.894034, -49.86651),
cluster = c("1", "1", "1", "1", "2", "2", "2", "2", "2", "2", "1", "1", "1", "1", "1", "1", "2", "2", "2", "2", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1"))
pts <- vect(data.frame(pdata), c("Longitude", "Latitude"))
z <- voronoi(pts, mun)
z <- aggregate(z, "cluster")
z <- crop(z, mun)
plot(z, "cluster", col=c("blue", "green"), mar=0,
plg=list(x=-50.213, y=-24.889, title="Cluster"), main="")
Output
Second code:
library(tmap)
tm_shape(sf::st_as_sf(z)) +
tm_borders() +
tm_scale_bar(position = c("LEFT", "BOTTOM"))
Simply use (the scale bar is plotted in the lower right corner to avoid overlapping elements):
library(tmap)
colpal <- c("blue", "green")
tm_shape(sf::st_as_sf(z)) +
tm_fill(col = "cluster", palette = colpal) +
tm_borders() +
tm_scale_bar(position = c("RIGHT", "BOTTOM"))
To use circles instead of the squares you need to add a custom legend:
library(tmap)
colpal <- c("blue", "green")
tm_shape(sf::st_as_sf(z)) +
tm_fill(col = "cluster", palette = colpal, legend.show = F) +
tm_borders() +
tm_scale_bar(position = c("RIGHT", "BOTTOM"))+
tm_add_legend(type = "symbol",
labels = c("1", "2"),
col = colpal,
title = "cluster",
size = 1.5,
shape = 21)