Add point at map centre in ggplot in r

857 views Asked by At

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))
1

There are 1 answers

0
Martin C. Arnold On BEST ANSWER

You can compute the centroids by grouping the data by region and then modify for each group using purrr::group_modify():

centroids <- us %>% 
  group_by(region) %>% 
  group_modify(~ data.frame(centroid(cbind(.x$long, .x$lat))))

Then plot everything together:

ggplot(us, aes(x = long, y = lat)) + 
  geom_polygon(aes(group = group)) +
  geom_map(map = us, aes(map_id = region, fill = temp), color = 'grey') +
  geom_point(data = centroids, aes(lon, lat), col = "red")

enter image description here