How to extract New Mexico state from USA boundaries package in R - 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.

Related

Adding specific locations to shp map

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.

Neighboring Zipcodes from State Polygons

First time posting on SO
I have a shapefile that has the geometries for each Zipcode along with state name. I want to figure out which zipcodes lie on the state borders.
The way I figured to achieve this is by combining all zipcodes for each state and leading to the geometry for a state and then finding the neighboring zipcodes for each state.
I combined the zipcodes into states using:
state_shape <- shapefile %>% group_by(State) %>% summarise(geometry = sf::st_union(geometry))
But then when I try to find the neighboring zipcodes using poly2nb
state_nb <- poly2nb(st_geometry(state_shape))
It gives me an Error:
Error in poly2nb(st_geometry(state_shape)) : Polygon geometries required
I understand to find the border zipcodes I will have to pass the zipcode geometries in poly2nb, but the error persists.
Any help will be highly appreciated, also any other approaches to this problem are more than welcome.
Consider this example, built on the widely available North Carolina shapefile that is distributed with {sf} package.
What the example does is:
creates a border line of North Carolina by first dissolving the counties, and then casting the resulting multipolygon to a multilinestring
runs sf::st_touches() on the counties and borderline with sparse set to false; the result is a logical vector that can be used to subset the original shapefile (filtering out the counties that share a border with the NC border)
presents the results in a graphical format, using {ggplot2}; the bordering counties are blue and the rest just blank for context
library(sf)
library(dplyr)
library(ggplot2)
# all NC counties (from shapefile distributed with {sf})
shape <- st_read(system.file("shape/nc.shp", package="sf"))
# border, via dplyr::summarise() & cast as a linestring
border <- shape %>%
summarise() %>%
st_cast("MULTILINESTRING")
# logical vector of length nrow(shape)
neighbours <- sf::st_touches(shape,
border,
sparse = F)
# report results
ggplot() +
geom_sf(data = shape[neighbours, ], fill = "blue") + # border counties
geom_sf(data = shape, fill = NA, color = "grey45") # all counties for context

Mapping specific States and Provinces in R

I'm trying to use R to generate a figure with sample localities for my FieldBio project. So far, I've been able to map the US states I want, to map Canada (national border), to overlay these two maps; what I'd like to do, though, is to map the following states/provinces specifically, excluding the others:
California
Nevada
Utah
Colorado
Wyoming
Montana
Idaho
Washington
Oregon
British Columbia
Alberta
Here is the code I've been using so far:
>map('state', region = c('california', 'nevada', 'utah', 'colorado', 'wyoming', 'montana', 'idaho', 'oregon', 'washington'), xlim=c(-130,-90), ylim=c(30,60), fill=TRUE, col="gray95")
>map("worldHires","Canada", xlim=c(-130,-90), ylim=c(30,60), col="gray95", fill=TRUE, add=TRUE)
This produces a map with the desired states, but canada as a country (cut off at the delimitors I set).
Is there a way to do only the provinces I want? I think I know how to plot the points (I have them as a .csv with lat and long data) on top of this afterward.
I realize that (R: creating a map of selected Canadian provinces and U.S. states) is pretty similar, but I'm getting a little lost in the code for that particular example, and I don't need to highlight anything specific.
Thanks
Like this?
library(raster)
states <- c('California', 'Nevada', 'Utah', 'Colorado', 'Wyoming', 'Montana', 'Idaho', 'Oregon', 'Washington')
provinces <- c("British Columbia", "Alberta")
us <- getData("GADM",country="USA",level=1)
canada <- getData("GADM",country="CAN",level=1)
us.states <- us[us$NAME_1 %in% states,]
ca.provinces <- canada[canada$NAME_1 %in% provinces,]
us.bbox <- bbox(us.states)
ca.bbox <- bbox(ca.provinces)
xlim <- c(min(us.bbox[1,1],ca.bbox[1,1]),max(us.bbox[1,2],ca.bbox[1,2]))
ylim <- c(min(us.bbox[2,1],ca.bbox[2,1]),max(us.bbox[2,2],ca.bbox[2,2]))
plot(us.states, xlim=xlim, ylim=ylim)
plot(ca.provinces, xlim=xlim, ylim=ylim, add=T)
So this uses the getData(...) function in package raster to grab the SpatialPolygonDataFrames for US states and Canadian provinces from the GADM site. Then it extracts only the states you want (notice that the relevant attribute table field is NAME_1 and the the states/provinces need to be capitalized properly). Then we calculate the x and y-limits from the bounding boxes of the two (subsetted) maps. Finally we render the maps. Note the use of add=T in the second call to plot(...).
And here's a ggplot solution.
library(ggplot2)
ggplot(us.states,aes(x=long,y=lat,group=group))+
geom_path()+
geom_path(data=ca.provinces)+
coord_map()
The advantage here is that ggplot manages the layers for you, so you don't have to explicitly calculate xlim and ylim. Also, IMO there is much more flexibility in adding additional layers. The disadvantage is that, with high resolution maps such as these (esp the west coast of Canada), it is much slower.

Overlay decimal coordinates (New Jersey) on NAD83 Stateplane polygon in R

I am trying to make a plot with points (decimal coordinates in New Jersey) on polyline shapefile with projection NAD 83 Stateplane (feet) (New Jersey). How can I do it? So far, I could plot the points and the shapefile separately but cannot overlay.
Plotted the shapefile using the following code:
orgListLayers("Counties.shp") # Shows the available layers for the shpaefile "Counties:
shape=readOGR("Counties.shp", layer="Counties") # Load the layer of the shapefile
plot(shape) # Plots the shapefile
Plotted points (vectors are lat1,long1) using the following code after transforming the points into Stateplane in ArcGIS:
dpts <- as.data.frame(cbind(long1,lat1))
plot(dpts2)
How can I overlay these points on the polyline shapefile?
Ultimately, I will have multiple sets of points which I want to plot on the shapefile as circles whose size would be dependent on values associated with the points. e.g. if each point represents a town, I want a bigger circle for a town having higher population.
You didn't provide any data, so this may be a partial answer.
Using the ggplot package it is easy to create layered maps. This map, of universities in NJ, was created with the code snippet that follows. It demonstrates plotting points and boundaries on the same map, and sizing the points based on a datum of the university (here, enrollment).
library(ggplot2)
library(rgdal)
setwd("<directory containing your data and maps")
states <- readOGR(dsn=".",layer="tl_2013_us_state")
nj.map <- states[states$NAME=="New Jersey",]
univ.map <- readOGR(dsn=".",layer="NJ_College_Univ_NAD83njsp")
nj.df <- fortify(nj.map)
univ.df <- univ.map#data
univ.df$ENROLL <- as.numeric(as.character(univ.df$ENROLL))
# create the layers
ggMap <- ggplot(nj.df)
ggMap <- ggMap + geom_path(aes(x=long,y=lat, group=group)) # NJ boundary
ggMap <- ggMap + geom_point(data=univ.df, aes(x=X, y=Y, size=ENROLL),color="red", alpha=0.7)
ggMap <- ggMap + coord_fixed()
ggMap <- ggMap + scale_size_continuous(breaks=c(5000,10000,15000,20000,25000,30000), range=c(0,10))
# render the map
ggMap
The TIGER/Line shapefile of US States was obtained here. The NJ Universities were obtained here.
Explanation:
The call to ggplot(...) defines the NJ map as the default dataset.
The call to geom_path(...) adds a layer to draw the NJ boundary.
The call to geom_point(...) adds a point layer locating the universities, with point size proportional to enrollment.
The call to coord_fixed(...) ensures that the map will not be distorted.
The call to scale_size_continuous(...) establishes breaks for the legend labels.

How to block a part of the level plot in R made using lattice package?

I have made a level plot in R of a variable using the lattice package. This grid corresponds to South Asia. I am only interested in viewing the values of this variable (aerosol optical depth) for certain countries in South Asia. I have a dummy variable that takes the value 1 for the countries I am interested in and 0 otherwise. Is it possible for me to colour this part of the grid black or any other colour?
I cannot show the level plot as I am low on reputation with stackoverflow. (The pdf that was attached to the crossposted message to rhelp should now appear:)
Here is my R code:
levelplot(aod ~ longitude + latitude | factor(day), data = aod_Jan,
aspect="iso", contour = TRUE, layout=c(1,1))
Since you are using geographical data, maybe the raster package is useful for you. For example, let's display the altitude of France (download this zip file or use the raster::getData function). After you unzip the file:
library(raster)
fraAlt <- raster('FRA_alt')
plot(fraAlt) ## Not only France is displayed...
If you want to display only the altitude of France, you need the information of the boundaries: download this RData file (or use the raster::getData function). This RData contains a SpatialPolygonsDataFrame (named gadm) which can be converted to a Raster with:
mk <- rasterize(gadm, fraAlt)
Now you can mask the altitude raster with the boundaries:
fraAltMask <- mask(fraAlt, x)
plot(fraAltMask) ##Now only France is displayed
Finally, if you want to use lattice methods you need the rasterVis package:
library(rasterVis)
levelplot(fraAlt)
levelplot(fraAltMask)
Now, all together with the boundaries superimposed:
s <- stack(fraAlt, fraAltMask)
layerNames(s) <- c('Alt', 'AltMask')
boundaries <- as(gadm, 'SpatialLines')
levelplot(s) + layer(sp.lines(boundaries))
Use the subset argument to levelplot. Perhaps:
levelplot(aod ~ longitude + latitude | factor(day), data = aod_Jan, subset = dummy==1,
aspect="iso", contour = TRUE, layout=c(1,1))

Resources