R 在美国地图上的2个邮政编码之间画一条线
我一直在试图画一条直线连接美国的2个邮政编码。到目前为止,我只能在美国绘制每个邮政编码的点,但无法在它们之间划出界限 以下是我的数据。我试图在美国地图上画8个点,用4条线把它们连接起来。我尝试使用zip.plot,但它只能指向点,不能画线R 在美国地图上的2个邮政编码之间画一条线,r,R,我一直在试图画一条直线连接美国的2个邮政编码。到目前为止,我只能在美国绘制每个邮政编码的点,但无法在它们之间划出界限 以下是我的数据。我试图在美国地图上画8个点,用4条线把它们连接起来。我尝试使用zip.plot,但它只能指向点,不能画线 df1 <- data.frame(trip = c(1,2,3,4), zip1 = c(55803,87112,55107,66006), zip2=c(12909,93703,12205,78210)) df1 trip zip1 zip
df1 <- data.frame(trip = c(1,2,3,4), zip1 = c(55803,87112,55107,66006), zip2=c(12909,93703,12205,78210))
df1
trip zip1 zip2
1 1 55803 12909
2 2 87112 93703
3 3 55107 12205
4 4 66006 78210
查看forzip.plot
函数,您会发现它非常简单。它会将您的邮政编码数据与数据(zip)
中的经度和纬度数据合并。您会注意到它将打印点,但没有连接点的函数,也不会返回打印的点
您可以根据需要调整类似的功能。如果包含library(muRL)
,则可以通过data(zips)
加载zip数据。绘制点后,可以根据trip
变量添加线以连接点
例如,创建一个新函数zip.plot.new
:
library(muRL)
data(zips)
zip.plot.new <- function(data, map.type = "state", ...){
data.z <- merge(data, zips[,c("zip", "lat", "lon")], by.x = "zip", by.y = "zip", all.x = TRUE)
maps::map(map.type, ...)
points(data.z$lon, data.z$lat, cex = 1, col = "black", pch = 20)
mapply(lines, split(data.z$lon, data.z$trip), split(data.z$lat, data.z$trip))
}
请注意,数据中的邮政编码12909
不匹配(似乎无效?)
数据
df1 <- data.frame(trip = c(1,2,3,4),
zip_1 = c("55803","87112","55107","66006"),
zip_2 = c("12909","93703","12205","78210"))
请显示绘制点的代码。
df1 <- data.frame(trip = c(1,2,3,4),
zip_1 = c("55803","87112","55107","66006"),
zip_2 = c("12909","93703","12205","78210"))
library(ggmap)
library(maps)
library(ggplot2)
library(tidyverse)
MainStates <- map_data("state")
point_data <- df1 %>%
pivot_longer(cols = starts_with("zip_"), names_to = c(".value", "group"), names_sep = "_") %>%
mutate(zip = factor(zip, levels = levels(zips$zip))) %>%
left_join(zips)
ggplot() +
geom_polygon(data=MainStates, aes(x=long, y=lat, group=group), color = "black", fill = "white") +
geom_point(data = point_data, aes(x = lon, y = lat, group = trip)) +
geom_line(data = point_data, aes(x = lon, y = lat, group = trip)) +
coord_fixed(1.3) +
theme_nothing()