I'm a New R user so not quite comfortable with the language.
Attempting to plot the locations of bird records on a map of Manchester, England.
have managed to create a map with following code
mymap<-get_map(c(lon=53.46388,lat=-2.294037),zoom=3,col="bw")
Have read spreadsheet as an xlsx file from excel via gdata, columns containing both long and lat assigned to Lon & Lat.
Seem to be able to qplot lon&lat but not as a layer on the map, when I attempt this I get the following error
Error: ggplot2 doesn't know how to deal with data of class list
I've now tried so many combinations of code it would be impossible for me to offer a demonstrative line on how I'm attempting to attach the data onto my map, have followed tutorials online to no avail - is it a problem in my xlsx file?
Edited: Sample code :
#Here is what Jamie Dunning tried:
require(ggmap)
origin<-c("Worsley,Salford","Elton reservoir","Etherow country park","Blackleach country park","Low Hall,LNR, Wigan","Cheadle royal","Rhodes lodges,Middleton","Persons flash,Wigan","Sale water park","Plattfields","Higher Boarshaw","Clifton country park","Horrocks flash")
ringing.origins<-geocode(origin)
map<-c(get_map("Greater Manchester")
swans.coor<-cbind(ringing.origins$lon,ringing.origins$lat)
I'm yet to have an example where they are plotted successfully.
Another Alternative using plotGoogleMaps
1- Get coordinates
require(ggmap)
#List places to find GPS coordinates for:
origin<-c("Worsley,Salford","Elton reservoir","Etherow country park","Elton reservoir","Blackleach country park","Low Hall,LNR, Wigan","Cheadle royal","Rhodes lodges,Middleton","Persons flash,Wigan","Sale water park","Plattfields","Higher Boarshaw","Clifton country park","Horrocks flash")
#Get coordinates via geocode function
ringing.origins<-geocode(origin)
#Put these coordinates in a data frame for creating an SP object later
df <- as.data.frame(origin)
row.names(df) <- 1:nrow(df)
2- Create Spatial Object
require(sp)
#Coordinates must be numeric and binded together as one element and rows numbered:
ringing.origins$lon <- as.numeric(ringing.origins$lon)
ringing.origins$lat <- as.numeric(ringing.origins$lat)
coord <- cbind(ringing.origins$lon,ringing.origins$lat)
row.names(coord) <- 1:nrow(coord)
#Define a mapping projection
AACRS <- CRS("+proj=longlat +ellps=WGS84")
#Creating a spatial object of "df" using the binded coordinates "coord":
Map2 <- SpatialPointsDataFrame(coord, df, proj4string = AACRS, match.ID = TRUE)
3-Create an interactive html googlemap:
require(plotGoogleMaps)
#Simple Map
plotGoogleMaps(Map2)
#Map with some options, filename creates a file in the working directory.
plotGoogleMaps(Map2, mapTypeId="ROADMAP", colPalette="red", legend=FALSE, filename="Swan_Map.htm")
Plotting using ggmap
require(ggmap)
#Get your coordinates
origin<-c("Worsley,Salford","Elton reservoir","Etherow country park","Elton reservoir","Blackleach country park","Low Hall,LNR, Wigan","Cheadle royal","Rhodes lodges,Middleton","Persons flash,Wigan","Sale water park","Plattfields","Higher Boarshaw","Clifton country park","Horrocks flash")
ringing.origins<-geocode(origin)
#Map of Greater Manchester
map<-get_map("Greater Manchester")
ggmap(map, extent = 'normal') +
geom_point(aes(x = lon, y = lat), data = ringing.origins)
#Box is too small...
#Bounding box with All points
mymap<-get_map(c(lon=-2.294037,lat=53.46388),zoom=10)
ggmap(mymap, extent = 'device') +
geom_point(aes(x = lon, y = lat), data = ringing.origins, alpha = 1)
Related
I'm trying to upload some of my analysis from R into ArcGIS but there isn't any coordinate points when I upload it. In my original CSV file I had coordinate points but lose them when I create a spatial dataframe???
#read csv file into r and then omit all the NAs
all_baboon <- read.csv(file = 'All_GPS_Collar_Data.csv')
baboon_GPS <- na.omit(all_baboon)
#create spatial dataframe by first creating new table with just individuals and x y coordinates
baboon.sp <- baboon_GPS[, c("Baboon", "X","Y")]
#create spatial points data frame
coordinates(baboon.sp) <- c("X", "Y")
str(baboon.sp)
#set coordinate referene system
proj4string(baboon.sp) <- CRS( "+proj=utm + zone=37 + datum=WGS84 +units=m +no_defs")
#calculate MCPs for each social group, 100% of points used in this scenario
baboon.mcp <- mcp(baboon.sp, percent=100)
baboon.mcp
I followed a tutorial for using adehabitat to find the home range of baboons. I can plot the home ranges in R, but haven't put a map down as the background because I want to import it as a shapefile into arcGIS. However, when I created a shapefile, theres no coordinates so the points and polygons don't get placed on the map.
shapefile(x = baboon.mcp, file = ".../baboonmcp.shp")
writeOGR(baboon.mcp, dsn = "...file_location", layer = "baboon.mcp", driver = "ESRI Shapefile")
I've tried it using shapefile and writeOGR but still have nothing. How can I add back the coordinates from the original csv file so it can be plotted in arcGIS?
Maybe the problem come from writeOGR, see writeOGR, read OGR does not provide X Y coordinates, which I need after clipping shapefile in R It's maybe better to use writeSpatialShape from the maptools package, you can try.
I'm working on a project which involves GPS coordinates from offshore locations. I'm looking to measure the distance from shore for each of my points. I have created a shapefile of the shoreline in question in QGIS and I have successfully imported it into R using the st_read() function (named "biminishore" in this example).
With the following code, I'm able to plot my shapefile in ggplot2:
bplot = ggplot() +
geom_sf(data = biminishore, size = 0.1, color = "black", fill = "green1") +
ggtitle("Bimini, The Bahamas") +
coord_sf() +
theme_classic()
plot(bplot)
Now, I would like to add the location coordinates (imported into R as a .csv with separate columns for Lat and Lon) as a layer over the imported shapefile. Can anyone suggest how to go about doing this in a way that will allow me to calculate the distance between each point and the nearest shoreline point?
My currents attempts are giving the error: Error in st_transform.sfc(st_geometry(x), crs, ...) : cannot transform sfc object with missing crs
I assume this means my coordinate systems are incompatible but haven't found a way around this yet. So far, I have tried combining my point columns using SpatialPoints(). I've also tried using multiple forms of st_set_crs() and st_transform() but I haven't had any luck yet. Any help is greatly appreciated! Thanks!
Read your points file as a csv & then transform it to an sf object:
library(tidyverse)
library(sf)
points <- read_csv('path_to_points.csv')
#make it an sf object, change Long and Lat to the correct column name
points_sf <- st_as_sf(points, coords = c("Long", "Lat"))
# set crs of points_sf to same as biminishore object
points_sf <- st_set_crs(points_sf, st_crs(biminishore))
Then you should be able to plot them together by adding:
+ geom_sf(data = points_sf)
to your ggplot2 call.
Finding the nearest feature between the two can be done with sf::st_nearest_feature(points_sf, biminishore).
A good post on nearest features & distances: https://gis.stackexchange.com/questions/349955/getting-a-new-column-with-distance-to-the-nearest-feature-in-r
I have the longitude and latitude of 5449 trees in NYC, as well as a shapefile for 55 different Neighborhood Tabulation Areas (NTAs). Each NTA has a unique NTACode in the shapefile, and I need to append a third column to the long/lat table telling me which NTA (if any) each tree falls under.
I've made some progress already using other point-in-polygon threads on stackoverflow, especially this one that looks at multiple polygons, but I'm still getting errors when trying to use gContains and don't know how I could check/label each tree for different polygons (I'm guessing some sort of sapply or for loop?).
Below is my code. Data/shapefiles can be found here: http://bit.ly/1BMJubM
library(rgdal)
library(rgeos)
library(ggplot2)
#import data
setwd("< path here >")
xy <- read.csv("lonlat.csv")
#import shapefile
map <- readOGR(dsn="CPI_Zones-NTA", layer="CPI_Zones-NTA", p4s="+init=epsg:25832")
map <- spTransform(map, CRS("+proj=longlat +datum=WGS84"))
#generate the polygons, though this doesn't seem to be generating all of the NTAs
nPolys <- sapply(map#polygons, function(x)length(x#Polygons))
region <- map[which(nPolys==max(nPolys)),]
plot(region, col="lightgreen")
#setting the region and points
region.df <- fortify(region)
points <- data.frame(long=xy$INTPTLON10,
lat =xy$INTPTLAT10,
id =c(1:5449),
stringsAsFactors=F)
#drawing the points / polygon overlay; currently only the points are appearing
ggplot(region.df, aes(x=long,y=lat,group=group))+
geom_polygon(fill="lightgreen")+
geom_path(colour="grey50")+
geom_point(data=points,aes(x=long,y=lat,group=NULL, color=id), size=1)+
xlim(-74.25, -73.7)+
ylim(40.5, 40.92)+
coord_fixed()
#this should check whether each tree falls into **any** of the NTAs, but I need it to specifically return **which** NTA
sapply(1:5449,function(i)
list(id=points[i,]$id, gContains(region,SpatialPoints(points[i,1:2],proj4string=CRS(proj4string(region))))))
#this is something I tried earlier to see if writing a new column using the over() function could work, but I ended up with a column of NAs
pts = SpatialPoints(xy)
nyc <- readShapeSpatial("< path to shapefile here >")
xy$nrow=over(pts,SpatialPolygons(nyc#polygons), returnlist=TRUE)
The NTAs we're checking for are these ones (visualized in GIS): http://bit.ly/1A3jEcE
Try simply:
ShapeFile <- readShapeSpatial("Shapefile.shp")
points <- data.frame(long=xy$INTPTLON10,
lat =xy$INTPTLAT10,
stringsAsFactors=F)
dimnames(points)[[1]] <- seq(1, length(xy$INTPTLON10), 1)
points <- SpatialPoints(points)
df <- over(points, ShapeFile)
I omitted transformation of shapefile because this is not the main subject here.
I have a spatial polygon object and a spatial points object. The latter was created from xy latlong data vectors (called latitude and longitude, respectively) in a dataframe, while the former was simply read into R directly using rgdal. My code is as follows:
boros <- readOGR(dsn = ".", "nybb")
rats <- read.csv("nycrats_missing_latlong_removed_4.2.14.csv", header = TRUE)
coordinates(rats) <- ~longitude + latitude
At this point neither spatial object is projected. If I project these objects as follows:
proj4string(boros) <- CRS("+proj=lcc")
proj4string(rats) <- CRS("+proj=lcc")
Both objects are now projected, and both will successfully map with the plot() function as follows:
plot(boros)
plot(rats)
However when I try to plot them together:
plot(boros)
plot(rats, add = TRUE)
I get the first plot only, without the rats object superimposed over boros. However, and this is the big problem, I get NO error message, so I have been unable to determine where the disconnection is between these two spatial objects being able to speak to each other. Both commands run smoothly without error or warning, yet I am left with just the single plot. And when I check the projections of each object with proj4string() I get the same projection returned for each object.
I have now spent many, many hours over several days trying various ways of creating two spatial objects whose CRS and projections match such that they can be mapped together using plot(). Incidentally, one approach I took was to create a shapefile in ArcGIS for the rats object, which worked fine to create the file. But I am still left with the same inability of the two spatial objects to work together in R. I have tried many different projections for both objects, spTransform on both objects, nothing seems to work.
Any help would be most appreciated. I have also included a dropbox link with the 2 data files I have described above:
https://www.dropbox.com/sh/x0urdo6guprnw8y/tQdfzSZ384
So, as some of the comments point out, the problem is that your data and your maps have different projections.
It looks like your map comes from the NYC Department of City Planning. The shapefile is definitely not in WGS84 (longlat), but the CRS is not included in the file (which is very disappointing by the way...). Nevertheless, there is a metadata file which indicates that the shapefile is projected as EPSG 2263.
In order to make use of this in R we need a projection string. The idiomatic way to get this in R is:
library(rgdal)
EPSG <- make_EPSG()
NY <- with(EPSG,EPSG[grepl("New York",note) & code==2263,]$prj4)
NY
# [1] "+proj=lcc +lat_1=41.03333333333333 +lat_2=40.66666666666666 +lat_0=40.16666666666666 +lon_0=-74 +x_0=300000.0000000001 +y_0=0 +datum=NAD83 +units=us-ft +no_defs"
Now we can either take your map and reproject that into WGS84, or take your data and reproject that into the map CRS.
setwd("< directory with all your files >")
data <- read.csv("nycrats_missing_latlong_removed_4.2.14.csv")
# First approach: reproject map into long-lat
wgs.84 <- "+proj=longlat +datum=WGS84"
map <- readOGR(dsn=".",layer="nybb",p4s=NY)
map.wgs84 <- spTransform(map,CRS(wgs.84))
map.wgs84.df <- fortify(map.wgs84)
library(ggplot2)
ggplot(map.wgs84.df, aes(x=long,y=lat,group=group))+
geom_path()+
geom_point(data=data, aes(x=longitude,y=latitude, group=NULL),
colour="red", alpha=0.2, size=1)+
ggtitle("Projection: WGS84 longlat")+
coord_fixed()
# Second approach: reproject data
map.df <- fortify(map)
rats <- SpatialPoints(data[,c("longitude","latitude")],proj4string=CRS(wgs.84))
rats <- spTransform(rats,CRS(NY))
rats.df <- data.frame(coordinates(rats))
ggplot(map.df, aes(x=long,y=lat,group=group))+
geom_path()+
geom_point(data=rats.df, aes(x=longitude,y=latitude, group=NULL),
colour="red", alpha=0.2, size=1)+
ggtitle("Projection: NAD83.2263")+
coord_fixed()
No rats in Central Park?
Thanks to suggestions from #AriBFriedman and #PaulHiemstra and subsequently figuring out how to merge .shp files, I have managed to produce the following map using the following code and data:
Data:
Morocco and Western Sahara
Code:
# Loading administrative coordinates for Morocco maps
library(sp)
library(maptools)
library(mapdata)
# Loading shape files
Mor <- readShapeSpatial("F:/Purdue University/RA_Position/PhD_ResearchandDissert/PhD_Draft/Country-CGE/MAR_adm1.shp")
Sah <- readShapeSpatial("F:/Purdue University/RA_Position/PhD_ResearchandDissert/PhD_Draft/Country-CGE/ESH_adm1.shp")
# Ploting the maps individually
png("Morocco.png")
Morocco <- readShapePoly("F:/Purdue University/RA_Position/PhD_ResearchandDissert/PhD_Draft/Country-CGE/MAR_adm1.shp")
plot(Morocco)
dev.off()
png("WesternSahara.png")
WesternSahara <- readShapePoly("F:/Purdue University/RA_Position/PhD_ResearchandDissert/PhD_Draft/Country-CGE/ESH_adm1.shp")
plot(WesternSahara)
dev.off()
# Merged map of Morocco and Western Sahara
MoroccoData <- rbind(Mor#data,Sah#data) # First, 'stack' the attribute list rows using rbind()
MoroccoPolys <- c(Mor#polygons,Sah#polygons) # Next, combine the two polygon lists into a single list using c()
# summary(MoroccoData)
# summary(MoroccoPolys)
offset <- length(MoroccoPolys) # Next, generate a new polygon ID for the new SpatialPolygonDataFrame object
browser()
for (i in 1: offset)
{
sNew = as.character(i)
MoroccoPolys[[i]]#ID = sNew
}
ID <- c(as.character(1:length(MoroccoPolys))) # Create an identical ID field and append it to the merged Data component
MoroccoDataWithID <- cbind(ID,MoroccoData)
MoroccoPolysSP <- SpatialPolygons(MoroccoPolys,proj4string=CRS(proj4string(Sah))) # Promote the merged list to a SpatialPolygons data object
Morocco <- SpatialPolygonsDataFrame(MoroccoPolysSP,data = MoroccoDataWithID,match.ID = FALSE) # Combine the merged Data and Polygon components into a new SpatialPolygonsDataFrame.
Morocco#data$id <- rownames(Morocco#data)
Morocco.fort <- fortify(Morocco, region='id')
Morocco.fort <- Morocco.fort[order(Morocco.fort$order), ]
MoroccoMap <- ggplot(data=Morocco.fort, aes(long, lat, group=group)) +
geom_polygon(colour='black',fill='white') +
theme_bw()
Results:
Individual maps
Merged Map:
Question:
I want to eliminate the boundary that cuts through the middle of the map? Anyone with any suggestions and/or help?
Thx all
I did achieve the elimination of the extra polygon layer that cuts the map in two after merging by using QGIS software, which is free to download at this link QGIS