I'm learning how to make maps with R so I'm kinda new to all of this. I'm using tmap to plot a map (you can find the shp here https://www.data.rio/datasets/%C3%A1reas-program%C3%A1ticas-da-sa%C3%BAde/explore).
I also have a dataframe that looks like this:
data <- data.frame(COD_AP_SMS = c("AP 1.0", "AP 2.1", "AP 2.2", "AP 3.1", "AP 3.2", "AP 3.3", "AP 4.0", "AP 5.1", "AP 5.2", "AP 5.3"),
n = c(11, 21, 6, 32, 15, 32, 27, 26, 19, 18))
I'm trying to plot a map where the colors of the polygons are different for each COD_AP_SMS and add n points to each polygon. For example, AP 1.0 would plot 11 points in it's polygon. Is it possible? Here's my code
ap <- read_sf("shp/Limites AP.shp")
plot(ap)
ap <- full_join(ap, tb, by = "COD_AP_SMS")
# make some bbox magic
bbox_new <- st_bbox(ap) # current bounding box
xrange <- bbox_new$xmax - bbox_new$xmin # range of x values
yrange <- bbox_new$ymax - bbox_new$ymin # range of y values
# bbox_new[1] <- bbox_new[1] - (0.25 * xrange) # xmin - left
bbox_new[3] <- bbox_new[3] + (0.25 * xrange) # xmax - right
# bbox_new[2] <- bbox_new[2] - (0.25 * yrange) # ymin - bottom
bbox_new[4] <- bbox_new[4] + (0.2 * yrange) # ymax - top
bbox_new <- bbox_new %>% # take the bounding box ...
st_as_sfc() # ... and make it a sf polygon
tm_shape(ap, bbox = bbox_new)+
tm_fill("COD_AP_SMS", auto.palette.mapping=FALSE,
title="AP")+
tm_dots("n", size = 2) +
tm_compass(position = c("left", "top"))+
tm_scale_bar(position = c("left", "top"))+
tm_borders(alpha=1, lwd = 1, col = "black")+
tm_legend(legend.format = list(text.separator= "a")) +
tm_layout(legend.position = c("right", "top"),
frame = FALSE)
Tips on how to make laebls, scale bar and compass look better are welcome.
The desired output would look something like this:
You can add shapes from multiple objects to a tmap by adding a new
tm_shape()
for each. To generate a set of random points,sf
providesst_sample()
function which is also able to generate points by polygon.