将坐标映射到世界地图并标记它们

Mapping coordinates to the world map and labeling them

我有一个包含三列的数据框:city_name、经度、纬度。使用 ggplot 我试图使用经度和纬度作为坐标来可视化数据,它们代表给定的城市。我还想用城市名称标记每个点。不幸的是比例不太正确,所以这些点被映射到正确的位置。

数据帧的示例数据:

    city_name <- c("Berlin", "Brussels", "Paris")
    longitude <- c("13.405", "4.3517", "2.3522")
    latitude <- c("52.52", "50.8503", "48.8566")
    df <- data.frame(city_name, longitude, latitude)

我正在使用 ggplot2。

mapWorld <- borders("world", colour="gray50", fill="gray50") # create a layer of borders
ggplot(df, aes(x= longitude, y= latitude, label=Name))+
  geom_point() +geom_text(aes(label=city_name),hjust=0, vjust=0) + mapWorld

当前结果: https://imgur.com/K3RvqTm

预期结果是将坐标映射到正确位置。

提前谢谢大家!

问题似乎源于您的经纬度数据格式。不要引用每个坐标,只需引用它们而不用引号。

我还推荐 leaflet 以获得更广泛的映射功能。下面的代码对我有用:

longitude <- c(13.405, 4.3517, 2.3522)
latitude <- c(52.52, 50.8503, 48.8566)
df <- data.frame(city_name, longitude, latitude)
library(leaflet)
df$longitude<-as.numeric(df$longitude)
df$latitude<-as.numeric(df$latitude)
leaflet() %>% 
  addTiles()%>% 
  addMarkers(data=df,lng=~longitude,lat=~latitude) %>% 
    setView(10,50,zoom=4)

除了已经提供的解决方案之外,您可能会发现查看 sf 包很有帮助,在我看来,它使空间数据的使用更加愉快。例如你可以这样做:

library(ggrepel)
library(sf)
library(ggplot2)


mapWorld <- borders("world", colour="gray50", fill="gray50") # create a layer of borders

# define data frame ensuring lat and lon are numeric vectors
df <- data.frame(city_name =  c("Berlin", "Brussels", "Paris"),
                 longitude =  c(13.405, 4.3517, 2.3522),
                 latitude = c(52.52, 50.8503, 48.8566))


# convert into an sf object, letting it know the columns we want to use for X and Y
# setting crs = 4326 for lon/lat data and remove = F to stop those columns from being dropped

df_sf <- st_as_sf(df, coords=c('longitude', 'latitude'), crs = 4326, remove = F)

# it plays nicely with ggplot via the 'geom_sf' geom
ggplot(df_sf)+
  mapWorld +
  geom_sf() +
  geom_text_repel(aes(x=longitude, y=latitude,label=city_name))

您会注意到 sf 对象带有它们自己的 'geometry' 列,该列可以被识别并且可以很好地与 ggplot 配合使用。需要注意的一件事是注意图层顺序 - 通过将 mapWorld 作为最后一层添加到你的 ggplot 中,它将出现在绘图的最顶部并且可能会覆盖你的点!