首页 > 解决方案 > 在 r 中的 ggplot 中的地图中心添加点

问题描述

我想在每个州中心加点。

centroid()geosphere包中知道可以做到这一点。它只能计算一个经度和纬度,但我有49个州,我不想一一计算。

我也知道coordinates()sp包可以做到这一点。它需要参数类输入SpatialPolygonsDataFramespus我从中获得的地图map_data()是一个数据框。

有什么建议吗?

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

标签: rdictionaryggplot2dplyrgeosphere

解决方案


您可以通过将数据分组来计算质心,region然后使用以下方法修改每个组purrr::group_modify()

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

然后将所有内容绘制在一起:

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

在此处输入图像描述


推荐阅读