r - 在 r 中的 ggplot 中的地图中心添加点
问题描述
我想在每个州中心加点。
我centroid()
从geosphere
包中知道可以做到这一点。它只能计算一个经度和纬度,但我有49个州,我不想一一计算。
我也知道coordinates()
从sp
包可以做到这一点。它需要参数类输入SpatialPolygonsDataFrame
,sp
但us
我从中获得的地图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))
解决方案
您可以通过将数据分组来计算质心,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")
推荐阅读
- r - 查找数据框中出现次数最多的列
- php - org.json.JSONException:java.lang.String 类型的值 DB 无法转换为 JSONObject
- javascript - 涉及数组的for循环问题
- json - 尝试解析带引号的 JSON 响应时出错
- php - PHP输入类型“datetime-local”:在编辑模式下不显示值
- bootstrap-4 - How can I append the date to the input field?
- python - 星际争霸以 python-sc2 启动,但加载屏幕后没有任何反应
- vb.net - 将 csv 文件克隆到内存并在数据表中使用它?(vb.net)
- reactjs - 测试自定义钩子并获得“警告:测试中对 TestHook 的更新未包含在行为中
- scala - Spark SQL join 真的很懒吗?