R: Custom cuts using `choropleth` in `{GISTools}` - r

I am plotting some data on a shapefile using R and choropleth in {GISTools}
I would like to modify my code below in order to assign custom breaks.
using the World Borders Dataset, download from: http://thematicmapping.org/downloads/TM_WORLD_BORDERS_SIMPL-0.3.zip
library(GISTools)
library(rgdal)
shape_file <- readOGR(dsn ="/home/hamid/TM_WORLD_BORDERS_SIMPL-0.3", layer = "TM_WORLD_BORDERS_SIMPL-0.3")
shades <-auto.shading(shape_file#data$POP2005, cutter = quantileCuts, n=5, cols = brewer.pal(5, "Blues"))
choropleth(shape_file, shape_file#data$POP2005, shading = shades)
choro.legend(70.00000,32.50000, shades)
Can anyone help please?

Related

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

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)

Base R Choropleth: colors aren't being applied to the map according to the order of the interval/breaks which makes the map hard to read

I created a choropleth with base R but I'm struggling with the colors. First, the colors don't follow the same order as the intervals and second, two of the intervals are using the same color, all of which makes the graph hard to read. This happens regardless of how many colors I use. It also doesn't matter whether I'm using brewer.pal or base colors.Here is a map with its respective legend illustrating the issue.
Below are the statements that I use to create the graph once data has been downloaded:
#Relevant packages:
library(dplyr)
library(RColorBrewer)
library(rgdal)
#create colors vector
pop_colors <- brewer.pal(8,"Purples")
#create breaks/intervals
pop_breaks <- c(0,20000,40000,60000,80000,100000,120000)
#apply breaks to population
cuts <- cut(cal_pop$Pop2016, pop_breaks, dig.lab = 6)
#create a vector with colors by population according to the interval they belong to:
color_breaks <- pop_colors[findInterval(cal_pop$Pop2016,vec = pop_breaks)]
Create choropleth
plot(cal_pop,col = color_breaks, main = "Calgary Population (2016)")
#create legend
legend("topleft", fill = color_breaks, legend = levels(cuts), title = "Population")
I used readOGR() command to read the shape file, which I'm linking here in case anybody is interested in taking a look at the data.
I'd appreciate any advice you could give me.
Thanks!
Your error is in this line:
color_breaks <- pop_colors[findInterval(cal_pop$Pop2016,vec = pop_breaks)]
I can't read your data file, so I'll use a built-in one from the sf package.
library(sf)
nc <- readOGR(system.file("shapes/", package="maptools"), "sids")
str(nc#data)
colors <- brewer.pal(8,"Purples")
#create breaks/intervals
sid_breaks <- c(0,2,4,6,8,10,12,20,60)
#apply breaks to population
sid_cuts <- cut(nc$SID79, sid_breaks, dig.lab = 6, include=TRUE)
#create a vector with colors by population according to the interval they belong to:
sid_colors <- colors[sid_cuts]
#Create choropleth
par(mar=c(0,0,0,0))
plot(nc, col = sid_colors)
legend("bottomleft", fill = colors, legend = levels(sid_cuts), nc=2, title = "SID (1979)", bty="n")

Plotting a world map on R without ggplot2

I'm trying to plot a world map on R but I don't have the version updated for ggplot2. Is there a way of doing it without?
You can get an extremely simple world map with:
library(maps)
map('world', fill = TRUE, col = 2:8, wrap=c(-180,180) )
And a somewhat better map from the mapdata package
library(mapdata)
map('worldHires', fill=TRUE, col=2:8)
And just for fun, here is a version with prettier colors, a blue ocean and cutting out Antarctica.
RegHR <- map("worldHires", namesonly=TRUE, plot=FALSE)
map('worldHires', fill=TRUE, col=terrain.colors(6), bg="#CCEEFF",
region=RegHR[-grep("Antarctica", RegHR)])

Plotting regions and adding color in leaflet R

I need to plot a map of Denmark divided into regions (there are 5: Region Nordjylland, Midtjylland, Sydjylland, Sjælland and Hovedstaden) and then color the regions such that the different regions stand out clearly. I have to use leaflet, since it has other features, that I will use later. I found a map on naturalearthdata.com, that I think I can use, but I can't figure out how to color (or even indicate) the regions. The code I tried is below
library(rgdal)
library(leaflet)
download.file(file.path('http://www.naturalearthdata.com/http/',
'www.naturalearthdata.com/download/50m/cultural',
'ne_50m_admin_1_states_provinces_lakes.zip'),
f <- tempfile())
unzip(f, exdir=tempdir())
world <- readOGR(tempdir(), 'ne_50m_admin_1_states_provinces_lakes', encoding='UTF-8')
DK <- subset(world, name=="Denmark")
leaflet() %>% addTiles() %>% addTopoJSON(DK, weight = 1, color = "#444444", fill = TRUE)
How does one use the naturalearthdata.com data to plot regions/states/provinces of different countries? I have seen a very nice example at
http://www.56n.dk/kort/dk2050kort_age.html
but there is no sample code available.
I have also found a very nice example here: https://rpubs.com/walkerke/leaflet_choropleth - but I need a map of Denmark.
UPDATE: I have found a shapefile at http://www.kortforsyningen.dk which does the trick. So now my question is how do I combine my own data with a shapefile and plot it in leaflet? If I just put
DK <- readOGR(".../shape", layer="REGION")
leaflet(data=DK)
I get a blank screen...

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)

Resources