I am new to spatial data. My goal is to get the gpx files from openstreetmap and plot polygons of Hungary's boundaries. I could successfully plot the boundaries under Járások but there are some boundaries under Kistérségek which are messed up, containing loops between points.
Image
Reproducable example for a specific boundary
library(XML)
library(magrittr)
library(sp)
parsed <- xmlParse("http://osmrm.openstreetmap.de/gpx.jsp?relation=1368104") %>% xmlToList()
coord <- do.call(rbind, parsed$rte)
name <- coord[1, 1]
coord <- coord[-(1:2), ]
coord <- apply(coord, 2, as.numeric)
poly <- Polygons(list(Polygon(coord)), name)
sp <- SpatialPolygons(list(poly), proj4string = CRS("+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0"))
plot(sp)
Result
Is the error because I missed something, or is it simply an issue with openstreetmap data? Any help is appreciated.
Related
I have a point vector for the entire globe at 0.25 degree resolution.
library(terra)
library(rnaturalearth)
# create point data
ref_grid <- terra::ext(-180, 180, -90, 90)
ref_grid <- terra::rast(ref_grid)
res(ref_grid)<- 0.25
values(ref_grid)<-1 #dummy values
projections <- "+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0"
crs(ref_grid) <- projections
pts <- terra::as.points(ref_grid, values=TRUE, na.rm=TRUE)
# download world shapefile
world_shp <- rnaturalearth::ne_countries()
world_shp <- terra::vect(world_shp)
world_shp <- terra::project(world_shp, projections)
I want to extract those points that fall within a landmass i.e. remove all those points that are in the ocean. So I did this:
e <- terra::extract(world_shp, pts)
But it's been two hours now and this is still running. Is there any faster way to do this?
You should not transform raster data to vector data if you want efficiency. In this case, you can do the following in a second or so:
library(terra)
library(rnaturalearth)
ref_grid <- terra::rast(res=0.25)
world_shp <- rnaturalearth::ne_countries(returnclass="sf") |> vect()
ref_grid <- rasterize(world_shp, ref_grid)
p <- as.points(ref_grid)
(but perhaps, depending on what you do next, the last step should also be avoided)
Borrowing code from Rob Berry (http://rob-barry.com/2015/06/14/Mapping-in-R/), I make a map of NY city. I have many lat long points I wish to plot on the map. The problem is that plotting a map like this results in plot area way outside of reasonable lat long ranges, so I assume there must either be a way to convert my points to the map scale, or rescale the map so the plot space can lay down lat lon points with the points() function.
Here is the code from Rob Berry:
download.file(destfile = "nypp_15b.zip")
unzip(zipfile = "nypp_15b.zip")
library("rgdal")
nypp <- readOGR("nypp_15b", "nypp")
plot(nypp)
Nice map! But now notice the plot extents:
par(“usr”)
The plots space numbers look like 888196.7, 1092361.0, 114013.0, 278953.2, so clearly lat lon points like the ones below won't show up on the map. So how do I get my points to plot correctly on the map?
lat <- c(40.75002, 40.74317)
lon <- c(-73.96905 -74.00366)
The following doesn't work because the scale is so different:
points(lat,lon, col = “red”)
Thank you very much.
nypp is in projected coordinate system, so you need to change to coordinate system of your points or of nypp. You can do something like this :-
nypp <- readOGR("nypp_15b", "nypp")
## Check the CRS of nypp
crs(nypp)
## CRS arguments:
+proj=lcc +lat_1=40.66666666666666 +lat_2=41.03333333333333 +lat_0=40.16666666666666 +lon_0=-74 +x_0=300000
+y_0=0 +datum=NAD83 +units=us-ft +no_defs +ellps=GRS80 +towgs84=0,0,0
plot(nypp)
lat <- c(40.75002, 40.74317)
lon <- c(-73.96905, -74.00366)
df <- data.frame(lat, lon)
## Convert to spatial dataframe and change the coordinates of the points
coordinates(df) <- ~lon + lat
crs(df) <- CRS("+proj=longlat +datum=WGS84")
df <- spTransform(df, crs(nypp))
## Add points to the plot
points(df$lon, df$lat, col = "red", pch =19)
Result:
I already created a bubble plot using the following code:
library(ggplot2)
library(sp)
library(raster)
library(maps)
library(mapdata)
library(maptools)
library(gstat)
library(ggmap)
xy <- se_pp[,c("longitude_s", "latitude_s")]
nl <- getData('GADM', country="Netherlands", level=2) #raster data, format SpatialPolygonsDataFrame
# coercing the polygon outlines to a SpatialLines object
spl <- list("sp.lines", as(nl, "SpatialLines"))
SPDF <- SpatialPointsDataFrame(coords=xy, data=se_pp)
projection(SPDF)<- "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs +towgs84=0,0,0"
coordinates(SPDF)[1:5,] #retrieves spatial coordinates form the dataframe
bubble(SPDF, "Quantity", sp.layout=spl, main="Plaice Quantity (#/km2), end summer (Sand Engine)")
Now I get a map of the Dutch coast containing the bubble plot (via getData).
Unfortunately this is a very simple map.
I would like to have a satellite map of the same area, which shows more detail, to show my bubble plot.
Does anyone know if this is possible?
Thanks.
I am not sure if you still check SO. But, I leave one approach for you. You can play with the values in zoom to identify the best zoom for your purpose. The CRAN manual of ggmap offers you more examples. Please have a look.
map <- get_map(location = 'netherlands', zoom = 7,
source = 'google',
maptype = 'satellite')
ggmap(map)
I have already asked about plotting points dependent on region, but now my question is about overlaying points given by coordinations over gadm map. I want to show different meteostations, using data based on this site or here is data used in code I've tried using such code:
require(ggplot2)
library(maptools)
library(rgdal)
library(RColorBrewer)
library(gpclib)
library(rgeos)
library(PBSmapping)
gpclibPermit()
rus<-load("C://RUS_adm1.RData")
proj4.str <- CRS("+init=epsg:3413 +lon_0=105")
gadm.prj <- spTransform(gadm, proj4.str)
rus<-gadm.prj
met <- read.csv2('C:\\meteo.txt')
cds <- data.frame(
Longitude=met$Long,
Latitude=met$Lat)
k<-as.matrix(cds)
popSP <- SpatialPointsDataFrame(coords=k,met["Elevation"], proj4string=proj4.str)
spplot(popSP, sp.layout=list('sp.polygons', gadm.prj))
, following advice from already mentioneed question, but it ends up with plotting points w/o gadm layer , I guess it's because of non-mentioning regions
Sorry, if question is dumb, but I will be grateful for any help
Here is the answer. Thanks to flowla
Edited code a little bit, I could plot different plot according to elevation.
library(rgdal)
library(raster)
rus <- load("C://RUS_adm1.RData")
popSP <- met <- read.csv2("C://meteo.txt")
for (i in c(3, 4))
popSP[, i] <- popSP[, i] / 1000
coordinates(popSP) <- ~ Long + Lat
projection(popSP) <- projection(gadm)
# Reprojection to EPSG:3413 (see http://www.spatialreference.org/ref/epsg/3413/)
proj4.str <- CRS("+proj=stere +lat_0=90 +lat_ts=70 +lon_0=105 +k=1 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs")
gadm.prj <- spTransform(gadm, proj4.str)
popSP.prj <- spTransform(popSP, proj4.str)
col_no <- as.factor(as.numeric(cut(popSP.prj$Elevation,
c(0,2500,5000,10000,15000,20000,100000))))
levels(col_no) <- c("<2500", "2500-5000","5000-10000", "10000-15000","15000-20000",">20000" )
color = rainbow(6)
popSP.prj$col_no<-col_no
spplot(popSP.prj, "col_no", sp.layout=list('sp.polygons',cols="ID_0", gadm.prj), col.regions=color, main="Meteostations in Russia", key.space="right")
sI have the dataset (pts) like this:
x <- seq(-124.25,length=115,by=0.5)
y <- seq(26.25,length=46,by=0.5)
z = 1:5290
longlat <- expand.grid(x = x, y = y) # Create an X,Y grid
pts=data.frame(longlat,z)
names(pts) <- c( "x","y","data")
I knew that I can map the dataframe (pts) into a map by doing:
library(sp)
library(rgdal)
library(raster)
library(maps)
coordinates(pts)=~x+y
proj4string(pts)=CRS("+init=epsg:4326") # set it to long, lat
pts = spTransform(pts,CRS(" +init=epsg:4326 +proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs +towgs84=0,0,0"))
pts <- as(pts, "SpatialPixelsDataFrame")
r = raster(pts)
projection(r) = CRS(" +init=epsg:4326 +proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs +towgs84=0,0,0")
plot(r)
map("usa",add=T)
Now I would like to create a separate map which shows the means of pts across different regions. The shapefile I want to use is from ftp://ftp.epa.gov/wed/ecoregions/cec_na/NA_CEC_Eco_Level2.zip , however, this is a north america map. How can I create the map showing only US based on this north america map? Or is there another better way to do this? thanks so much.
I think that cutting out the non-US data based on the data in the shapefile alone would be hard, since the regions do not correspond to political boundaries - that could be done with rgeos though.
Assuming that "eco" is a SpatialPolygonsDataFrame read in by rgdal::readOGR or maptools::readShapeSpatial, see the available key data for indexing:
sapply(as.data.frame(eco), function(x) if(!is.numeric(x)) unique(x) else NULL)
If you just want to plot it, set up a map with only the US region to start with and then overplot.
library(maps)
map("usa", col = "transparent")
We see that the data is in Lambert Azimuthal Equal Area:
proj4string(eco)
[1] " +proj=laea +lat_0=45 +lon_0=-100 +x_0=0 +y_0=0 +a=6370997 +b=6370997 +units=m +no_defs"
So
require(rgdal)
eco.laea <- spTransform(eco, CRS("+proj=longlat +ellpse=WGS84"))
plot(eco.laea, add = TRUE)
If you want to plot in the original Lambert Azimuthal Equal Area you'll need to get the bounding box in that projection and start the plot based on that, I just used existing data to make an easy example. I'm pretty sure the data could also be cropped with rgeos against another boundary too, but depends what you actually want.