I want to add point at every state centre.
I know centroid() from geosphere package can do this. It can only compute one longitude and latitude, but I have 49 states and I do not want to compute it one by one.
I also know coordinates() from sp package can do this. It needs the argument class input is SpatialPolygonsDataFrame and sp but the us map I get from map_data() is a dataframe.
Any suggestion?
library(scatterpie)
library(tidyverse)
library(geosphere)
library(ggnewscale)
us <- map_data('state') %>% as_tibble()
n = length(unique(us$region))
# creat fake mapping data
temperature_data <- tibble(region = unique(us$region),
temp = rnorm(n = n))
coords <- us %>% select(long, lat, region) %>% distinct(region, .keep_all = T)
coords_data <- tibble(region = unique(us$region)) %>% left_join(coords)
us <- left_join(us, temperature_data)
# add point
p + geom_map(map = us, aes(map_id = region, fill = temp), color = 'grey') +
geom_point(data = category_data, aes(long, lat))
You can compute the centroids by grouping the data by
regionand then modify for each group usingpurrr::group_modify():Then plot everything together: