Plotting country borders with maptools - R - r

Following the excelent post from Joe Wheatley (http://joewheatley.net/ncep-global-forecast-system/) I managed to produce a
temperature global map. But, instead of only plotting coastline I've tried to use maptools package to plot country borders.
The problem comes when only eastern hemisphere country borders are plotted. I should be missing something I can't figure out,
still looking for on stackoverflow and google. Hope you can help.
Here is the code I'm using (most coming from Joe's post)
loc=file.path("ftp://ftp.ncep.noaa.gov/pub/data/nccf/com/gfs/prod/gfs.2013052100/gfs.t00z.sfluxgrbf03.grib2")
download.file(loc,"temp.grb",mode="wb")
system("wgrib2 -s temp.grb | grep :TMP: | wgrib2 -i temp.grb -netcdf TMP.nc",intern=T)
system("wgrib2 -s temp.grb | grep :LAND: | wgrib2 -i temp.grb -netcdf temp.nc",intern=T)
library(ncdf)
landFrac <-open.ncdf("LAND.nc")
lon <- get.var.ncdf(landFrac,"longitude")
lat <- get.var.ncdf(landFrac,"latitude")
temp=open.ncdf("TMP.nc")
t2m.mean <- get.var.ncdf(temp,"TMP_2maboveground")
library("fields")
library("sp", lib.loc="/usr/lib/R/site-library")
library("maptools", lib.loc="/usr/lib/R/site-library")
day="DIA"
png(filename="gfs.png",width=1215,height=607,bg="white")
rgb.palette <- colorRampPalette(c("snow1","snow2","snow3","seagreen","orange","firebrick"), space = "rgb")#colors
image.plot(lon,lat,t2m.mean,col=rgb.palette(200),main=as.expression(paste("GFS 24hr Average 2M Temperature",day,"00 UTC",sep="")),axes=T,legend.lab="o C")
data(wrld_simpl)
plot(wrld_simpl, add = TRUE)
dev.off()
and this is the image produced
This is a global map, should I use xlim and ylim in image.plot to extract a region (i.e. Europe)
EDIT: Added url for temp.nc file
http://ubuntuone.com/29DKAeRjUCiCzLblgfSLc9
Any help would be appreciated, thanks

The data set wrld_simpl is aligned on longitudes [-180, 180] but your grid data is clearly [0,360]. Since you have maptools loaded try this to add a modified copy to your plot:
plot(elide(wrld_simpl, shift = c(360, 0)), add = TRUE)
There are other tools to crop and move/combine and recentre data like this, including ?rotate in the package raster. It really depends on what you need.
Another graphics-alternative is to just use "world2" in the maps package
library(maps)
map("world2", add = TRUE)
Either of those will work to finish your plot started above.
Here's another discussion related to this: Fixing maps library data for Pacific centred (0°-360° longitude) display

You can do this:
library(raster)
r <- raster("temp.nc")
r <- rotate(r)
plot(r)

Related

Can I "turn off" arrows where the value is 0 in vectorplot? (no currents on land)

I am trying to make a map of Guam's current field using vectorplot in the rasterVis package. When I read in my original data where the currents on "land" were NA, I got errors so I am instead using a file where velocity on land is 0. But this means I get current vector arrows on land in my plot.
Is it possible to "tell" the plot not to plot vectors if the value =0? I am very new to rasterVis and grateful for any advice!
NetCDF file for current data can be found here: https://drive.google.com/drive/folders/12h9jN0rI6An8kF56ugNhODtVa40Z8vV0?usp=sharing[![enter image description here]1]1
ncfile_org <- 'guaROMS_2021Apr25May21_nan.nc'
ucomp <- brick(ncfile_org, varname='u')
vcomp <- brick(ncfile_org, varname='v')
desired date to plot
d=181
ucomp1 <- ucomp[[d]]
vcomp1 <- vcomp[[d]]
ucomp1[is.na(ucomp1[])]=0
vcomp1[is.na(vcomp1[])]=0
uv=stack(ucomp1,vcomp1)
Plot Guam with current vectors. Note, I have changed the viridis palette so that "land" (velocity=0) is white.
vectorplot(uv,isField="dXY",region=TRUE,
par.setting=viridisTheme(region=c("#FFFFFFFF",viridis(10))))
Thank you so much for your help.

Global cartogram in R

I am trying to create a global cartogram using the cartogram package in R. I am trying to use the data from wrld_simpl. What I expect is a cartogram in which the Population ("Pop2005" variable) is plotted. The code I have developed is this:
data(wrld_simpl)
world<-wrld_simpl
world_sf = st_as_sf(world)
world_sf_proj = st_transform(world_sf, crs = 3785)
world_cartogram <- cartogram_cont(world_sf_proj, "POP2005")
plot(world_cartogram)
Nonetheless, this has resulted in the following figure:
Do you know what is wrong with the code? Maybe the CRS? I have tried to use others CRS but I got the following error:
"Error: Using an unprojected map. This function does not give correct centroids and distances for longitude/latitude data:
Use "st_transform()" to transform coordinates to another projection."
Taken from this documentation, it is stated that
The default plot of an sf object is a multi-plot of all attributes, up
to a reasonable maximum
If you want to use the base R plot function, then use st_geometry(your_map) to plot (the geometry) an sf object.
Another possibility (which I don't recommend) is to set plot options to 1 plot maximum (options(sf_max.plot=1)), but this plots the first variable, and it might not be the best idea.
library(sf)
library(spData)
library(cartogram)
library(tidyverse)
world_sf = st_as_sf(world)
world_sf_proj = st_transform(world_sf, crs = 3785)
world_cartogram <- cartogram_cont(world_sf_proj, "pop")
plot(st_geometry(world_cartogram))
Now, sf is particularly well suited with ggplot2 and the tidyverse. In that setting, just use ggplot in combination with geom_sf.
ggplot(world_cartogram) +
geom_sf()

Mapping my data to a Zip Code area map in R

My data is like this:
ZIPcode Cases longi lati
43613 1 -83.604452 41.704307
44140 1 -81.92148 41.48982
46052 1 -86.470531 40.051603
48009 22 -83.213883 42.544619
48017 6 -83.151815 42.535396
48021 7 -82.946167 42.463894
48025 19 -83.265758 42.523195
I want to get a map similar to this (if you can see it) in R. The outline should be zipcodes and the shading should be according to number of cases, darker as cases increase.
I'm very new to R. Tried a lot of code I found online but can't get what I want. Any help is appreciated. Can this be done in base SAS ?
Thank you!
enter image description here
Definetly you can do it in R, I put together a reprex (reproducible example) for you. Key points:
You need to load into R a .shp file (or .geojson, .gpkg, etc.). That is an actual file with the outline of your map. For ZIPCODES I found a R package, tigris, that does that for you, if not you'll need to load it by yourself.
For handling mapping objects (load, transform, .etc), sf package is your best friend.
For plotting, in this example I used cartography, but you can use several different package, as ggplot2 or tmap.
Last line is that, given your data (and if I didn't get the ZIPCODEs wrong), a map as the one you shown (choropleth map) maybe is not the best options. Have a look here to see other alternatives.
library(sf) #Overall handling of sf objects
library(cartography) #Plotting maps package
#1. Create your data
yourdata <- data.frame(ZCTA5CE10=c("43613", "44140", "46052",
"48009","48017", "48021","48025"),
Cases=c(1,1,1,22,6,7,19)
)
#2. Download a shapefile (shp,gpkg,geojson...)
library(tigris) #For downloading the zipcode map
options(tigris_use_cache = TRUE)
geo <- st_as_sf(zctas(cb = TRUE, starts_with = yourdata$ZCTA5CE10))
#Overall shape of USA states
states <- st_as_sf(states(cb=TRUE))
#For plotting, all the maps should have the same crs
states=st_transform(states,st_crs(geo))
#3. Now Merge your data
yourdata.sf=merge(geo,yourdata)
#4. Plotting
par(mar=c(1,1,1,1))
ghostLayer(yourdata.sf)
plot(st_geometry(states), add=TRUE)
choroLayer(yourdata.sf,
var="Cases",
add=TRUE,
border = NA,
legend.pos = "right",
legend.frame = TRUE)
layoutLayer(title = "Cases by ZIPCODE",
theme = "blue.pal",
scale = FALSE,
sources = "Source; your question on SO",
author = "by dieghernan, 2020"
)
Created on 2020-02-27 by the reprex package (v0.3.0)

Colorize the map of Russia depending on the variable in R

I have a map of Russia with regional subdivision
library(raster)
data <- getData('GADM', country='RUS', level=1)
http://www.gks.ru/bgd/regl/B16_14p/IssWWW.exe/Stg/d01/08-01.doc
The link is to a Word.doc with data (table) on crime rates for Russian regions. I can extract this data and use it in R. I want to take 2015 year and colorize regions on the map depending on the crime rate (also add a legend). How can I do this? The problem is that names of regions are sometimes different in the shape file (NL_NAME_1) and in the data from www.gks.ru.
I also have this code for graph that I need, except that here we have meaningless colors:
library(sp)
library(RColorBrewer)
data$region <- as.factor(iconv(as.character(data$NAME_1)))
spplot(data, "region", xlim=c(15,190), ylim=c(40,83),
col.regions=colorRampPalette(brewer.pal(12, "Set3"))(85), col = "white")
If I understand your question properly, you just need to add your data to the spatial object for making colors meaningful.
Note, please, that the data is a reserved word in R. So, it's better to modify a little your variable name:
geo_data <- getData('GADM', country = 'RUS', level = 1)
Let's emulate some data to demonstrate a visualization strategy:
set.seed(23)
geo_data#data["data_to_plot"] <- sample(1:100, length(geo_data#data$NAME_1))
Using a default GADM projection would cut the most eastern part of the country. A simple transformation helps to fit the whole area to a plot:
# fit Russian area inside the plot
geo_data_trsf <- spTransform(geo_data, CRS("+proj=longlat +lon_wrap=180"))
Draw the map selecting data_to_plot instead of region:
max_data_val <- max(geo_data_trsf#data$data_to_plot)
spplot(geo_data_trsf, zcol = "data_to_plot",
col.regions = colorRampPalette(brewer.pal(12, "Set3"))(max_data_val),
col = "white")
The plot limits are adjusted automatically for the transformed spatial data geo_data_trsf, making possible to omit xlim and ylim.
As for the problem with the names, I can't provide any ready-to-use solution. Obviously, the regions' names of NL_NAME_1 need some additional treatment to use them as labels. I think, it would be better to use NAME_1 as an identifier in your code to ensure that it'll be no troubles with encoding. The NL_NAME_1 column is perfectly suitable to set the correspondence between your Word-data and the data inside the spatial object geo_data.

R Highlighting some of the boundaries (or borders) of the region in a shape file with spplot()

I am working on a shape file and like to highlight some of the boundaries (borders) of the regions (as figure 1):
Figure 1: some but not all of the regions (borders) of the shape file are highlighted
(Source: https://dl.dropboxusercontent.com/u/48721006/highlighted.png)
The highlighting is achieved with ArcMap. I can't figure out how to do the same with R (particularly with the spplot()). Any suggestions on this?
To get the shape file
library(sp)
library(maptools)
con <- url("http://gadm.org/data/rda/ZAF_adm2.RData")
print(load(con))
close(con)
plot(gadm)
Many thanks!
G
What I would do: (1) plot the complete set; (2) take a subset; (3) plot the subset with a different line type. For subsetting shape files, check this question.
plot(gadm)
# check class and structure of the data
class(gadm)
head(gadm#data)
# take a subset based on ID_2
some_polygons = subset(gadm,ID_2>=38840 & ID_2<38850)
plot(some_polygons, add=T, border='cyan', lwd=2)

Resources