使用 r 中的 ggplot 添加点到 usmap

Mik*_*keF 7 r ggplot2 usmap

我能够通过本教程创建美国地图。当我尝试添加额外的点时,无论我输入什么数据,它们最终都会到达南达科他州。

library(ggplot2)
library(usmap)
testData <- data.frame(LATITUDE = 20.31557, LONGITUDE = -102.42547)
p <- plot_usmap( regions = "state") 
p + geom_point(data = testData, aes(x = LONGITUDE, y = LATITUDE), color = "red")
Run Code Online (Sandbox Code Playgroud)

Pao*_*olo 7

usmap 0.5.0开始,存在一个名为 的新函数usmap_transform,它可以转换 adata.frame以匹配 所使用的投影usmap

这是与您提供的数据类似的示例:

library(usmap)
library(ggplot2)

# Lat/Lon of Sioux Falls, SD
test_data <- data.frame(lon = -96.70, lat = 43.55)

transformed_data <- usmap_transform(test_data)

plot_usmap("states") + 
  geom_point(data = transformed_data, 
             aes(x = x, y = y), 
             color = "red",
             size = 3)
Run Code Online (Sandbox Code Playgroud)

显示美国地图上单个红点的绘图,该点是南达科他州苏福尔斯所在的位置

还有一个名为“高级映射”的新小插图更详细地显示了这一点。


hrb*_*str 3

这是一个“有趣”的包,与生成底层 shapefile 的博客文章代码相比没有太多增值(但包作者认为不适合在包中归功于博客文章的作者DESCRIPTION,只是一种策略- 到自述文件的末尾)。

作者还认为不适合做的一件事是为除分区统计图之外的任何内容提供支持。您的问题是地图位于一个坐标系中,而您的点位于另一个坐标系中。

如果你可以使用非 CRAN 包(在作者制作 copypasta 包之前就已经albersusa存在了一段时间)提供了必要的粘合剂:usamap

library(albersusa) # https://gitlab.com/hrbrmstr/albersusa / https://github.com/hrbrmstr/albersusa
library(ggplot2)
library(sp)
Run Code Online (Sandbox Code Playgroud)

获取预先投影的美国地图:

us <- usa_composite(proj = "aeqd")
Run Code Online (Sandbox Code Playgroud)

我们将使用内置的“state.center”数据来获取一些点

states_centers <- as.data.frame(state.center)
states_centers$name <- state.name
Run Code Online (Sandbox Code Playgroud)

但是,如果您查找 state.center 上的帮助,您会发现他们不提供阿拉斯加和夏威夷的合法坐标,我们无法使用它们:

states_centers <- states_centers[!(states_centers$name %in% c("Alaska", "Hawaii")),]
Run Code Online (Sandbox Code Playgroud)

注意:如果您在阿拉斯加/夏威夷有点,则需要使用包中的 'points_elided() 函数来修改任何阿拉斯加或夏威夷点。长期以来的 TODO 一直是支持points_elided()所有转换,但我几乎从不需要在 choropleths 之外使用该包,所以暂时它会是 TODO。

现在,通过从直长/纬度到投影坐标系,使它们成为我们地图的合法坐标:

coordinates(states_centers) <- ~x+y
proj4string(states_centers) <- CRS(us_longlat_proj)
states_centers <- spTransform(states_centers, CRSobj = CRS(us_aeqd_proj))
states_centers <- as.data.frame(coordinates(states_centers))
Run Code Online (Sandbox Code Playgroud)

并且绘制它们:

us_map <- fortify(us, region="name")

ggplot() +
  geom_map(
    data = us_map, map = us_map,
    aes(x = long, y = lat, map_id = id),
    color = "#2b2b2b", size = 0.1, fill = NA
  ) +
  geom_point(
    data = states_centers, aes(x, y), size = 4, color = "steelblue"
  ) +
  coord_equal() + # the points are pre-projected
  ggthemes::theme_map()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • @Paolo 我还想指出 `usmap` 确实有一个增值功能。它不依赖于非 R 库,例如“geos”和“gdal”,如果您没有环境的管理员访问权限,这可能会出现问题。所以谢谢你的包裹。有没有办法使用包裹的对比色来投影州和县的边界? (2认同)