r - 在r中的ggplot中添加 map 中心点

标签 r dictionary ggplot2 dplyr geosphere

我想在每个州中心添加点。

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

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

有什么建议吗?

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

最佳答案

您可以通过按区域对数据进行分组来计算质心,然后使用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")

enter image description here

关于r - 在r中的ggplot中添加 map 中心点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64288986/

相关文章:

c# - 为什么 Lookup 在 C# 中是不可变的?

R:了解 object.size() 如何与内存使用相关

R:绘图区域上方的 ggrepel、ggplot2 标签

r - 将数据框中的列乘以另一个数据框中给出的值

r - 使用 ggplot2 在箱线图旁边创建垂直不重叠的标签

Python:检查变量是否是字典

c# - 在字典中查找最匹配的单词

r - 高分辨率数据的 ggplot 平滑优化

r - 在 r 中使用 max() 函数返回向量中的值及其名称?

r - 在 str_replace/stri_replace 中使用捕获的组 - stringi vs stringr