在R中使用ggplot将点添加到usmap [英] Add points to usmap with ggplot in r

查看:45
本文介绍了在R中使用ggplot将点添加到usmap的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用

I was able to create a US map with this tutorial. When I tried to add additional points to it they all ended up in South Dakota, no matter what I input for data.

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

解决方案

That's an "interesting" package that doesn't have much value-add over the blog post code the underlying shapefiles were generated from (yet the package author did not see fit to credit the author of the blog post in the package DESCRIPTION, just a tack-on to the end of a README).

One thing the author also did not see fit to do is provide support for anything but choropleths. Your problem is that the map is in one coordinate system and your points are in another.

If you can use non-CRAN packages, albersusa (which was around for a while before the usamap author did the copypasta package) provides the necessary glue:

library(albersusa) # https://gitlab.com/hrbrmstr/albersusa / https://github.com/hrbrmstr/albersusa
library(ggplot2)
library(sp)

Get the US map pre-projected:

us <- usa_composite(proj = "aeqd")

We'll use built-in "state.center" data to get some points

states_centers <- as.data.frame(state.center)
states_centers$name <- state.name

However, if you look up the help on state.center you'll see that they don't provide legit coords for Alaska & Hawaii, we we can't use them:

states_centers <- states_centers[!(states_centers$name %in% c("Alaska", "Hawaii")),]

NOTE: If you do have points in Alaska/Hawaii you need to se the 'points_elided() function in the package to modify any Alaska or Hawaii points. A longstanding TODO has been to make points_elided() support all the transforms but I almost never need to use the package outside of choropleths so it'll be TODO for a while.

Now, make them legit coords for our map by going from straight long/lat to the projected coordinate system:

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

And, plot them:

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

这篇关于在R中使用ggplot将点添加到usmap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆