【问题标题】:Mapping coordinates to the world map and labeling them将坐标映射到世界地图并标记它们
【发布时间】:2019-06-20 20:28:37
【问题描述】:

我有一个包含三列的数据框:城市名称、经度、纬度。使用 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

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

提前谢谢大家!

【问题讨论】:

    标签: r ggplot2 visualization


    【解决方案1】:

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

    我还推荐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)
    

    【讨论】:

      【解决方案2】:

      除了已经提供的解决方案之外,您可能会发现查看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 对象带有自己的“几何”列,该列被识别并与 ggplot 很好地配合使用。需要注意的一件事是要小心您的图层排序 - 通过将 mapWorld 作为最后一层添加到您的 ggplot 中,它将出现在绘图的最顶部并可能覆盖您的观点!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-09-18
        • 1970-01-01
        • 2015-08-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-07-31
        相关资源
        最近更新 更多