Adding specific locations to shp map - r

I am creating a map on R with the following commands:
map_and_data <- inner_join(mapshape, mapdata) // where mapshape is the shp file and mapdata contains the data
ggplot(map_and_data) +
geom_sf(aes(fill=covidcases))+
scale_fill_gradient(low = "white", high = "red4", name = "COVID-19 cases")+
theme_classic())
This produces a normal map by region showing the amount of COVID-19 cases. Then, I have an excel file with a list of the largest 20 cities and their coordenates, and I want to add to the map a point for each one of these cities. How can I overlay a point for the locations of these cities to the original map?
My dataset (previously shp) called map_data looks as follows:
region_code
geometry
080018
(((410315.5 4598889, 410888.8 4598870~
080039
(((384322.7 4625199, 384343.6 4625174~
Thank you in advance!

Your city coordinates are in a different coordinate system than the polygons in you shape file. You can sf::st_transform() them into the target CRS after reading them.

Related

How to extract New Mexico state from USA boundaries package in R

I am trying to make a Tmap with two points but I am having some issues.
`library(tmap)
library(maps)
library(sf)
library(USAboundaries)
#Open soil pit location data
data<-read.csv("SoilPit_Locations___.csv")
#Converting locations to an sf object
points<-st_as_sf(data,coords=c("Longitude","Latitude"),crs=4326)
#Set up map mode as view for an interactive map
tmap_mode("plot")
#Set up style as natural to view topography
tmap_style("natural")
#Map us borders and add points for locations as dots
#tm_shape(us) + tm_borders("black", lwd = .5) +
m=tm_shape(points)+tm_dots()
m
tmap_save(m, "my_mapp.png")`
The issue I am having is that when I try run my code the two points are on the corners of the map, I would like to plot them on the New Mexico state map so they can look nicer.
I have tried extracting the NM state boundary from the world map but I have been unsuccessful.
If you do:
library(USAboundariesData)
then you get states_contemporary_lores (amongst other things) which are the USA state boundaries, so you can subset NM like this:
nm = states_contemporary_lores[
states_contemporary_lores$state_abbr=="NM",
]
and then nm is an sf object which is just New Mexico. You can map this in tmap using tm_shape(nm) + tm_borders() and then adding whatever other layers you have.

How to get coordinates of cities from openstreetmap in R?

I have a vector of german city names, like
cities <- c("Munich", "Hamburg", "Gelsenkirchen", "Berlin", "Berlin", "Berlin", "Hamburg")
I would like to draw a map with red dots on any city in that list.
Specificly, I would like to
create an openstreetmap section, which is just wide enough to include all cities in the list
draw red points on the map for every city in the list, making the points bigger by the count of city names
(optimally) not care about the actual coordinates of the cities, as openstreetmap "should know" them
So, how would I do this in R with ggplot?
This is how I got so far:
library(OpenStreetMap)
# List of cities
staedte <- tribble(
~Stadt, ~lon, ~lat,
"HSNR", 6.56964 , 51.31655,
"Mönchengladbach", 6.4519, 51.2007
)
# get the map (this might take some time)
# and add some extra margin of 0.015
mymap <-openmap(c(min(staedte$lat)-0.015, min(staedte$lon)-0.015),
c(max(staedte$lat+0.015), max(staedte$lon)+0.015),
type = "stamen-watercolor", mergeTiles = TRUE)
# project openstreetmap to alternate coordinate system (might also take some time)
mymap_coord <- openproj(mymap)
# create a ggplot2-Object of the map
mymap_plt <- OpenStreetMap::autoplot.OpenStreetMap(mymap_coord)
# add the city points
mymap_plt +
geom_point(data=staedte, aes(x=lon, y=lat, size=10), color="blue") +
geom_text(data=staedte, aes(x=lon, y=lat+0.01, size=10, label=Stadt), color="blue")
This works quiet well. My problem is:
right now I have to enter the lon and lat coordinates of the city by hand. Is there a way to get them just by the city name?
how could I set the size of the points in relation to the count of the city?

How to add location points onto a shapefile imported into R from QGIS using ggplot2

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

Plotting Latitude and Longitude over a map

I'm currently using ggmaps to display a map of the location I'm trying to display points over but when I use the points function to try to add the points over the map it says that my list of latitudes and longitudes cannot be used for the arguments in x and y. Is there any better way to plot the points other than having to go one by one and individually code them onto my map?
Edit: Here's the data I'm working with right now and the first few lines of code that aren't working-
-A table of 2 variables "lat" and "lon" that show all the points geocoded
-A list of the addresses where the geo coordinates came from
mapTampa <- get_map(location = 'Tampa', zoom = 10)
points(lon, lat, col = "red", cex = 0.5)
The first line works and gives me the map but when I tried to add points thats when it gave me the x y error so I tried:
finalMap<-mapTampa+geom_point(aes(x=lon, y=lat, data=Filtered_Data))
Where latlong is my table with both latitudes and longitudes but that doesn't work either. I'm fairly new to R and this is my first project working with it but it seems like I've read everything about ggplot and ggmap and nothing is helping me.

trouble plotting data in the ggmap package for R

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)

Resources