I try to add points with custom coordinates to a map. In general, this seems to work with the NC map provided by the sf package. However, it does not work in a shapefile I downloaded from
ggplot()
geom_sf(data = ger_shape)
coord_sf(lims_method = "geometry_bbox")
geom_point(data = city2, aes(x = lng, y = lat), color = 'red')
ggplot()
geom_sf(data = nc)
geom_sf(data = ger_shape)
coord_sf(lims_method = "geometry_bbox")
geom_point(data = city, aes(x = lng, y = lat), color = 'red')
geom_point(data = city2, aes(x = lng, y = lat), color = 'red')
CodePudding user response:
Your problem is probably just an issue with your coordinate system (projected instead of geographic). I am just guessing since I don't want to download the shapefile from the link provided. Here is an example:
library(tidyverse)
library(sf)
nc <- st_read(system.file("shape/nc.shp", package="sf"))
city <- data.frame(name = "1", lat = 35.7721, lng = -78.63861)
#projected, no point
ggplot()
geom_sf(data = st_transform(nc, crs = st_crs("EPSG:32616")))
coord_sf(lims_method = "geometry_bbox")
geom_point(data = city, aes(x = lng, y = lat), color = 'red')
#geographic, point
ggplot()
geom_sf(data = nc)
coord_sf(lims_method = "geometry_bbox")
geom_point(data = city, aes(x = lng, y = lat), color = 'red')
Your problem will likely be fixed by setting the correct projection to use lat long coordinates:
ggplot()
geom_sf(data = st_transform(ger_shape, crs = st_crs("NAD27")))
coord_sf(lims_method = "geometry_bbox")
geom_point(data = city2, aes(x = lng, y = lat), color = 'red')
CodePudding user response:
The issue is that the coordinate reference system (crs) used by the shapefiles for Germany provided by the BKG is Gauss-Kruger zone 3 (check st_crs(ger_shape)
) which does not specify locations in degrees whereas you specified the city locations in degrees. As a result the coordinates for the cities are far away from Germany which you could see be dropping the coord_sf
line:
library("ggplot2")
library("sf")
nc <- st_read(system.file("shape/nc.shp", package="sf"))
ger_shape <- st_read("shp/VG250_LAN.shp")
ger_shape <- ger_shape[which(ger_shape$GF == 4),]
city2 <- data.frame(name = c("2","3"), lat = c(53,50), lng = c(10.2,10.2))
ggplot()
geom_sf(data = ger_shape)
geom_point(data = city2, aes(x = lng, y = lat), color = 'red')
Hence, to add your points to the map of Germany you have to specify the coordinates in the crs of the shape file or transform the crs to e.g. WGS84
using st_transform
which specifies locations in degrees:
ger_shape <- sf::st_transform(ger_shape, "WGS84")
ggplot()
geom_sf(data = ger_shape)
coord_sf(lims_method = "geometry_bbox", crs = st_crs(ger_shape))
geom_point(data = city2, aes(x = lng, y = lat), color = 'red')