Add latitud/longitud dot to my map is not working (R STUDIO) - r

I ploted an Argentina map and then I took the region I am interested in. But the problem is, I can not plot specific dots in specific latitudes and longitudes. It does not work.
And I want to plot different dots with values all over the map!!
This is the website where I took the data to plot the map: https://gadm.org/download_country_v3.html (I only downloaded a file, that was all).
library(sp)
gadm <- readRDS("gadm36_ARG_1_sf.rds")
gadm<-gadm[2]
plot(gadm)
mapaposta= plot(gadm, col = 'lightgrey', border = 'black',ylim = c(-40,-27),xlim=c(-68,-55))
points(-63.4,-34.1167,col=2)
This is the plot I am getting with no dots on it!!

You need to set the coordinate reference system of the spatial polygons data frame.
library(sp)
# download data from https://biogeo.ucdavis.edu/data/gadm3.6/Rsp/gadm36_ARG_1_sp.rds
gadm <- readRDS("gadm36_ARG_1_sp.rds")
proj4string(gadm)=CRS("+proj=longlat +datum=WGS84")
plot(gadm, col = 'lightgrey', border = 'black',ylim = c(-40,-27),xlim=c(-68,-55))
points(-63.4,-34.1167,col=2)

Related

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.

Add points (Lat-Lon) to a marmap plot

I would like to plot a series of lat-lon points of a seal track, each coloured according to an attribute, on to a map that shows the bathymetry (100m contours) and coastline. I learnt how to create a map to show the bathymetry+coastline using marmap and ggplot2. The code is here:
dat <- getNOAA.bathy(-58,-62.5,43,46.0,res=0, keep=TRUE)
plot(dat,image=TRUE,bpal = list(c(min(dat), 0, "darkblue", "blue","lightblue"), c(0, max(dat), "gray90","gray10")),drawlabels=TRUE,deep=c(-500,200,0),shallow=c(-500,100,0),step=c(500,100,0),lwd=c(1,1,1),lty=c(1,1,1),land=TRUE)+
scaleBathy(dat, deg=1.232, x="bottomleft", inset=5) #100km
This created a useful map. However, I am stalled over how to add the seal track on to this map.
I could do this in ggmap (using the code below) but I much prefer the marmap map
myLocation <- c(-62.5,43,-58,46)
seal_map2<-get_map(location=myLocation,maptype="watercolor",source="stamen",zoom=10)
ggmap(seal_map2)+
geom_point(data=sealtrack,aes(color=category),size=0.5)+
scale_color_gradientn(colours=rainbow(6), breaks=seq(1,6,by=1))
Any guidance will be much appreciated
You should be able to add the bathymetric info from marmap as a contour layer on your plot after "fortifying" it. Without your data it's difficult to make sure that it works (and the NOAA server is down for me right now):
library(ggplot2)
library(marmap)
dat <- getNOAA.bathy(-58,-62.5,43,46.0,res=0, keep=TRUE)
dat <- fortify(dat)
ggmap(seal_map2) +
geom_contour(dat, aes(x = x, y = y, z = z)) +
geom_point(data=sealtrack,aes(color=category),size=0.5) +
scale_color_gradientn(colours=rainbow(6), breaks=seq(1,6,by=1))

Overlap image plot on a Google Map background in R

I'm trying to add this plot of a function defined on Veneto (italian region)
obtained by an image and contour:
image(X,Y,evalmati,col=heat.colors(100), xlab="", ylab="", asp=1,zlim=zlimits,main=title)
contour(X,Y,evalmati,add=T)
(here you can find objects: https://dl.dropboxusercontent.com/u/47720440/bounty.RData)
on a Google Map background.
I tried two ways:
PACKAGE RGoogleMaps
I downloaded the map mbackground
MapVeneto<-GetMap.bbox(lonR=c(10.53,13.18),latR=c(44.7,46.76),size = c(640,640),MINIMUMSIZE=TRUE)
PlotOnStaticMap(MapVeneto)
but i don't know the commands useful to add the plot defined by image and contour to the map
PACKAGE loa
I tried this way:
lat.loa<-NULL
lon.loa<-NULL
z.loa<-NULL
nx=dim(evalmati)[1]
ny=dim(evalmati)[2]
for (i in 1:nx)
{
for (j in 1:ny)
{
if(!is.na(evalmati[i,j]))
{
lon.loa<-c(lon.loa,X[i])
lat.loa<-c(lat.loa,Y[j])
z.loa<-c(z.loa,evalmati[i,j])
}
}
}
GoogleMap(z.loa ~ lat.loa*lon.loa,col.regions=c("red","yellow"),labels=TRUE,contour=TRUE,alpha.regions=list(alpha=.5, alpha=.5),panel=panel.contourplot)
but the plot wasn't like the first one:
in the legend of this plot I have 7 colors, and the plot use only these values. image plot is more accurate.
How can I add image plot to GoogleMaps background?
If the use of a GoogleMap map is not mandatory (e.g. if you only need to visualize the coastline + some depth/altitude information on the map), you could use the package marmap to do what you want. Please note that you will need to install the latest development version of marmap available on github to use readGEBCO.bathy() since the format of the files generated when downloading GEBCO files has been altered recently. The data from the NOAA servers is fine but not very accurate in your region of interest (only one minute resolution vs half a minute for GEBCO). Here is the data from GEBCO I used to produce the map : GEBCO file
library(marmap)
# Get hypsometric and bathymetric data from either NOAA or GEBCO servers
# bath <- getNOAA.bathy(lon1=10, lon2=14, lat1=44, lat2=47, res=1, keep=TRUE)
bath <- readGEBCO.bathy("GEBCO_2014_2D_10.0_44.0_14.0_47.0.nc")
# Create color palettes for sea and land
blues <- c("lightsteelblue4", "lightsteelblue3", "lightsteelblue2", "lightsteelblue1")
greys <- c(grey(0.6), grey(0.93), grey(0.99))
# Plot the hypsometric/bathymetric map
plot(bath, land=T, im=T, lwd=.03, bpal = list(c(0, max(bath), greys), c(min(bath), 0, blues)))
plot(bath, n=1, add=T, lwd=.5) # Add coastline
# Transform your data into a bathy object
rownames(evalmati) <- X
colnames(evalmati) <- Y
class(evalmati) <- "bathy"
# Overlay evalmati on the map
plot(evalmati, land=T, im=T, lwd=.1, bpal=col2alpha(heat.colors(100),.7), add=T, drawlabels=TRUE) # use deep= shallow= step= to adjust contour lines
plot(outline.buffer(evalmati),add=TRUE, n=1) # Outline of the data
# Add cities locations and names
library(maps)
map.cities(country="Italy", label=T, minpop=50000)
Since your evalmati data is now a bathy object, you can adjust its appearance on the map like you would for the map background (adjust the number and width of contour lines, adjust the color gradient, etc). plot.bath() uses both image() and contour() so you should be able to get the same results as when you plot with image(). Please take a look at the help for plot.bathy() and the package vignettes for more examples.
I am not realy inside the subject, but Lovelace, R. "Introduction to visualising spatial data in R" might help you
https://github.com/Robinlovelace/Creating-maps-in-R/raw/master/intro-spatial-rl.pdf From section "Adding base maps to ggplot2 with ggmap" with small changes and data from https://github.com/Robinlovelace/Creating-maps-in-R/archive/master.zip
library(dplyr)
library(ggmap)
library(rgdal)
lnd_sport_wgs84 <- readOGR(dsn = "./Creating-maps-in-R-master/data",
layer = "london_sport") %>%
spTransform(CRS("+init=epsg:4326"))
lnd_wgs84_f <- lnd_sport_wgs84 %>%
fortify(region = "ons_label") %>%
left_join(lnd_sport_wgs84#data,
by = c("id" = "ons_label"))
ggmap(get_map(location = bbox(lnd_sport_wgs84) )) +
geom_polygon(data = lnd_wgs84_f,
aes(x = long, y = lat, group = group, fill = Partic_Per),
alpha = 0.5)

Z - Values for polygon (shapefile) in R

my goal is to create a 3D-Visualization in R. I have a shapefile of urban districts (Ortsteile) in Berlin and want to highlight the value (inhabitants/km²) as a z-value. I have implemented the shapefile into R and coloured the value for desnity ("Einwohnerd") as followed:
library(rgdal)
library(sp)
berlin=readOGR(dsn="C...etc.", layer="Ortsteile")
berlin#data
col <- rainbow(length(levels(berlin#data$Name)))
spplot(berlin, "Einwohnerd", col.regions=col, main="Ortsteil Berlins", sub="Datensatz der Stadt Berlin", lwd=.8, col="black")
How it is posible to refer a certain polygon (urban district) to a z-value (inhabitant/km²) and how can I highlight this z-value?
Hope that someone will have an answer!
Best regars
SB
Thanks for the answer, but I am still on my wy to find out the best to use the density as z-value so that I can create a 3D Model. I found out that it is not possible to use the polygons of the shape but that it is possible to rasterize the polygon and to use a matrix for a different perspective and rotation.
Here is the code but the final 3D visualization looks not sharp and good enough. Maybe it would be better to calculate the the z-value in anther way so that the first values did not start so high or to use the center of the polygon and than to draw a column in z-direction:
library(rgdal)
library(sp)
setwd("C:\\...")
berlin=readOGR(dsn="C:\\...\\Ortsteile", layer="Ortsteile")
col <- rainbow(length(levels(berlin#data$Name)))
spplot(berlin, "Einwohnerd", col.regions=col, main="Ortsteil Berlins",
sub="Datensatz der Stadt Berlin", lwd=.8, col="black")
library(raster)
raster <- raster(nrows=100, ncols=200, extent(berlin))
test <- rasterize(berlin, raster, field="Einwohnerd")
persp(test, theta = 40, phi = 40, col = "gold", border = NA, shade = 0.5)
for(i in seq(0,90,10)){
persp(test, theta = 40, phi = i, col = "gold", border = NA, shade = 0.5)
}
library(rgl)
library(colorRamps)
mat <- matrix(test[], nrow=test#nrows, byrow=TRUE)
image(mat)
persp3d(z = mat, clab = "m")
persp3d(z = mat, col = rainbow(10),border = "black")
persp3d(z = mat, facets = FALSE, curtain = TRUE)
Is this what you had in mind?
library(ggplot2)
library(rgdal) # for readOGR(...) and spTransform(...)
library(RColorBrewer) # for brewer.pal(...)
setwd("<directory with shapefile>")
map <- readOGR(dsn=".",layer="Ortsteile")
map <- spTransform(map,CRS=CRS("+init=epsg:4839"))
map.data <- data.frame(id=rownames(map#data), map#data)
map.df <- fortify(map)
map.df <- merge(map.df,map.data,by="id")
ggplot(map.df, aes(x=long, y=lat, group=group))+
geom_polygon(aes(fill=Einwohnerd))+
geom_path(colour="grey")+
scale_fill_gradientn(colours=rev(brewer.pal(10,"Spectral")))+
theme(axis.text=element_blank())+
labs(title="Berlin Ortsteile", x="", y="")+
coord_fixed()
Explanation
This is a great question, in that it provides an example of a very basic choropleth map using ggplot in R.
Shapefiles can be read into R using readOGR(...), producing SpatialDataFrame objects. The latter have basically two sections: a polygons section containing the coordinates of the polygon boundaries, and a data section containing information from the attributes table in the shapefile. These can be referenced, respectively, as map#polygons and map#data.
The code above reads the shapefile and transforms the coordinates to epsg:4839. Then we prepend the polygon ids (stored in the rownames) to the other information in map#data, creating map.data. Then we use the fortify(...) function in ggplot to convert the polygons to a dataframe suitable for plotting (map.df). This dataframe has a column id which corresponds to the id column in map.data. Then we merge the attribute information (map.data) into map.df based on the id column.
The ggplot calls create the map layers and render the map, as follows:
ggplot: set the default dataset to map.df; identify x- and y-axis columns
geom_polygon: identify column for fill (color of polygon)
geom_path: polygon boundaries
theme: turn off axis text
labs: title, turn off x- and y-axis labels
coord_fixed: ensures that the map is not distorted
A note on scale_fill_gradientn(...): this function assigns colors to the fill values by interpolating a color palette provided in the colours= parameter. Here we use the Spectral palette from www.colorbrewer.org. Unfotrunately, this palette has the colors revered (blue - red), so we use rev(...) to reverse the color order (high=red, low=blue). If you prefer the more highly saturated colors common in matlab, use library(colorRamps) and replace the call to scale_fill_gradientn(...) with:
scale_fill_gradientn(colours=matlab.like(10))+

R - Add a map layer to geographical mapping

I am trying to map some data in R with the mercator map as a background.
Here is what is I am using, the data points come out fine, but I am not getting the map.
qplot(nt_phi_lambda$longitude, xlab='Longitude',
nt_phi_lambda$latitude, ylab='Latitude',
data=nt_phi_lambda, main='Global Indsutry Break-down',
colour=industry, projection='mercator()', parameters=c(0,0,0))
You need a data.frame with the coordinates of the country boundaries. Just setting projection = 'mercator() does not add a map in mercator projection. See a recent question of mine for an example of how to plot a world map. An example in a few lines of code:
require(maps)
world_map = data.frame(map(plot=FALSE)[c("x","y")])
ggplot(aes(x = x, y = y), data = world_map) + geom_path()
See also the documentation of coord_map.

Resources