【问题标题】:Drawing map with ggplot and draw dots in map使用 ggplot 绘制地图并在地图中绘制点
【发布时间】:2021-08-14 02:15:32
【问题描述】:

我使用苏格兰的酿酒厂处理数据集,我想在地图上可视化它们的位置。 所以我用下面的代码来画苏格兰和它的周边是这样的:

library(SpatialEpi)
library(tmap)
library("sf")
library("rnaturalearth")
library("rnaturalearthdata")
library("rgeos")
library("ggspatial")
library("ggrepel")

world <- ne_countries(scale = "medium", returnclass = "sf")
ggplot(data = world) +
  geom_sf() +
  coord_sf(xlim = c(-13.68, 0.72), ylim = c(54.63, 60.85), expand = FALSE)

之后,我使用数据集威士忌的经度/纬度信息,并尝试将酿酒厂绘制为点(数据集可以在这里下载:whisky):

whisky <- read.csv("whisky_data.csv")
mapdata <- whisky[,c(1,15:16)]
mapdata$Latitude <- as.numeric(mapdata$Latitude)
mapdata$Longitude <- as.numeric(mapdata$Longitude)

coordinates(mapdata)<-~Longitude+Latitude
class(mapdata)

# does it have a projection/coordinate system assigned?
proj4string(mapdata)  # Nope

# check coordinate system of world
st_crs(world)  # +proj=longlat +datum=WGS84

# manually tell R what the coordinate system is
proj4string(mapdata)<-CRS("+proj=longlat +datum=WGS84")

ggplot(data = world) +
  geom_sf() +
  coord_sf(xlim = c(-13.68, 0.72), ylim = c(54.63, 60.85), expand = FALSE) +
  geom_point(data=as.data.frame(mapdata), aes(x=Longitude, y=Latitude), color="red")

但是地图上没有显示任何点。 我想我没有正确转换坐标以绘制到世界地图中?

由于我是地图方面的绝对初学者,因此我非常感谢您对此提供的任何帮助! 非常感谢! :)

【问题讨论】:

    标签: r coordinates sf


    【解决方案1】:

    你的案子很浓/威士忌,多么可爱的词?

    考虑这段代码;它建立在 {sf} 包和 ggplot2::geom_sf() 函数之上。有关更多信息,请查看 RStudio 论坛上的这篇文章,讨论绘制地图的其他选项https://community.rstudio.com/t/best-packages-for-making-map-leaflet-vs-ggmap-vs-sf-vs/38403/2?u=jlacko

    但无论如何,这段代码应该可以帮助您入门。

    library(sf) # general spatial manipulation
    library(giscoR) # for the shape of Scotland
    library(dplyr) # general data frame manipulation
    library(ggplot2) # because ggplot...
    
    # Scotland as a spatial object
    scotland <- giscoR::gisco_get_nuts(nuts_id = 'UKM',
                                       resolution = '01') 
    
    # yer data
    distilleries <- read.csv("whisky_data.csv") %>% 
      st_as_sf(coords = c("Latitude", "Longitude"), crs = 4326)
    
    # a quick reality check - looks legit
    mapview::mapView(distilleries)
    
    # a ggplot object
    ggplot() +
      geom_sf(data = scotland, fill = NA, color = "gray45") + # borders of Scotland
      geom_sf(data = distilleries, pch = 4, color = "red") + # the distilleries
      theme_void() +
      labs(title = "Distilleries of Scotland") +
      theme(plot.title = element_text(hjust = 1/2))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-26
      • 2018-05-29
      • 2015-01-13
      相关资源
      最近更新 更多