我有一个德国城市名称的向量,比如
cities <- c("Munich", "Hamburg", "Gelsenkirchen", "Berlin", "Berlin", "Berlin", "Hamburg")
我想在该列表中的任何城市上绘制一张带有红点的地图。 具体来说,我想
那么,我该如何在 R 中使用 ggplot 来做到这一点?
这就是我到目前为止的情况:
library(OpenStreetMap)
# List of cities
staedte <- tribble(
~Stadt, ~lon, ~lat,
"HSNR", 6.56964 , 51.31655,
"Mönchengladbach", 6.4519, 51.2007
)
# get the map (this might take some time)
# and add some extra margin of 0.015
mymap <-openmap(c(min(staedte$lat)-0.015, min(staedte$lon)-0.015),
c(max(staedte$lat+0.015), max(staedte$lon)+0.015),
type = "stamen-watercolor", mergeTiles = TRUE)
# project openstreetmap to alternate coordinate system (might also take some time)
mymap_coord <- openproj(mymap)
# create a ggplot2-Object of the map
mymap_plt <- OpenStreetMap::autoplot.OpenStreetMap(mymap_coord)
# add the city points
mymap_plt +
geom_point(data=staedte, aes(x=lon, y=lat, size=10), color="blue") +
geom_text(data=staedte, aes(x=lon, y=lat+0.01, size=10, label=Stadt), color="blue")
这工作安静很好。我的问题是:
扩展上面 nwbort 关于您问题的坐标部分的评论:
osmdata
包是到达这里的最简单方法,因为您可以根据城市名称检索数据。然而,获取边界框而不是坐标有点烦人。这里建议使用一个函数来获取边界框,然后计算它的质心(使用简单特征 (sf
) 包)。
library(sf)
library(dplyr)
library(osmdata)
city_coords_from_op_str_map <- function(city_name){
city_coordinates <- osmdata::getbb(city_name) %>% # Obtain the bounding box corners fro open street map
t() %>% # Transpond the returned matrix so that you get x and y coordinates in different columns
data.frame() %>% # The next function takes a data frame as input
sf::st_as_sf(coords = c("x", "y")) %>% # Convert to simple feature
sf::st_bbox() %>% # get the bounding box of the corners
sf::st_as_sfc() %>% # convert bounding box to polygon
sf::st_centroid() %>% # get the centroid of the polygon
sf::st_as_sf() %>% # store as simple feature
sf::`st_crs<-`(4326) # set the coordinate system to WGS84 (GPS etc.)
city_coordinates %>%
dplyr::mutate(name_of_city = city_name) %>% # add input city name in a column
dplyr::rename(geometry = x) %>% # Rename the coordinate column
dplyr::relocate(name_of_city, geometry) %>% # reorder the columns
return()
}
alingsas <- city_coords_from_op_str_map("Alingsås") # Store coordinate of a city
travemunde <- city_coords_from_op_str_map("Travemünde") # Store coordinate of a city
cities_of_interest <- bind_rows(alingsas, travemunde) # join data of the different cities
对于问题的第二部分,我没有代码建议,但是如果您将每个城市的人口规模放在另一列中,您可以使用该列来定义图中符号的大小。