Display SpatialPolygonsDataFrame on leaflet map with R - r

I would like to display the polygon of Canada on a leaflet map.
# create map
library(leaflet)
m = leaflet() %>% addTiles()
m
I was able to find the polygon for Canada: http://www.gadm.org/country.
I chose the SpatialPolygonsDataFrame format for R, but there are other formats available (such as Shapefile)
# load object in R
load("country_polygons/CAN_adm0.RData")
pol_can <- gadm
How can I display the shape on the map? I assume I have to leverage the sp package but I could not figure out how to do so.
Many thanks in advance for your help!

You can pass a SpatialPolygons* object to the addPolygons function as per Section 2.2 of the docs here.
For example (note that the following includes a ~11.4 MB download):
library(sp)
download.file('http://biogeo.ucdavis.edu/data/gadm2/R/CAN_adm0.RData', f <- tempfile())
load(f)
leaflet() %>% addTiles() %>% addPolygons(data=gadm, weight=2)
Note that GADM data can also be downloaded with the getData function in the raster package:
library(raster)
can <- getData('GADM', country='VAT', level=0)
EDIT
In response to the comments, I really like the lightweight polygon datasets that Natural Earth provides. Here's an example where I download the 1:50,000,000 countries shapefile (Admin 0) from Natural Earth, subset it to the current members of the Commonwealth of Nations, and plot those. The zipped shapefile is under 1 MB.
library(rgdal)
library(leaflet)
download.file(file.path('http://www.naturalearthdata.com/http/',
'www.naturalearthdata.com/download/50m/cultural',
'ne_50m_admin_0_countries.zip'),
f <- tempfile())
unzip(f, exdir=tempdir())
world <- readOGR(tempdir(), 'ne_50m_admin_0_countries', encoding='UTF-8')
commonwealth <- c("Antigua and Barb.", "Australia", "Bahamas", "Bangladesh",
"Barbados", "Belize", "Botswana", "Brunei", "Cameroon", "Canada", "Cyprus",
"Dominica", "Fiji", "Ghana", "Grenada", "Guyana", "India", "Jamaica", "Kenya",
"Kiribati", "Lesotho", "Malawi", "Malaysia", "Maldives", "Malta", "Mauritius",
"Mozambique", "Namibia", "Nauru", "New Zealand", "Nigeria", "Pakistan", "Papua
New Guinea", "Rwanda", "St. Kitts and Nevis", "Saint Lucia", "St. Vin. and
Gren.", "Samoa", "Seychelles", "Sierra Leone", "Singapore", "Solomon Is.",
"South Africa", "Sri Lanka", "Swaziland", "Tanzania", "Tonga", "Trinidad and
Tobago", "Tuvalu", "Uganda", "United Kingdom", "Vanuatu", "Zamibia")
leaflet() %>% addTiles() %>%
addPolygons(data=subset(world, name %in% commonwealth), weight=2)

Related

R mutate() and case_when() does not add values to the new field

I created a new field where I intend to populate some data(continents) from some vectors, based on data of an existing column(country). There are several datasets involved in the analysis and the code worked perfectly on only the last table, but the other tables which are as much of importance failed to fill in continents to the required column.
meats_long <- meats_long %>%
add_column(Territory = NA)
Africa <- c("Cote d'Ivoire", "Madagascar", "South Africa", "Ghana", "Morocco", "Ethiopia", "Kenya","Egypt")
NorthAmerica <- c("Mexico","Panama","Jamaica", "Dominican Republic","Nicaragua","Honduras","Costa Rica","Guatemala","Canada","El Salvador")
Europe <- c("Iceland","Belgium-Luxembourg","Ukraine","Latvia","Sweden","Greece","Portugal","Russia","Poland","Denmark","Norway","Switzerland","Austria","Germany","Netherlands","Spain","France","Italy","Ireland","United Kingdom")
Asia <- c("Taiwan","Turkey", "Pakistan","Japan","China","Vietnam", "Hong Kong","Thailand","India","Indonesia","Philippines","Korea, South","Malaysia","Israel","Sri Lanka","Pakistan")
Oceania <- c("Australia","Other Pacific Islands, NEC")
SouthAmerica <- c("Uruguay","Bolivia","Colombia","Argentina","Ecuador","Peru","New Zealand", "Brazil","Chile")
Others <- c("Rest of world")
meats_long <- meats_long %>%
mutate(Territory = case_when(Source %in% Africa ~ "Africa",
Source %in% NorthAmerica ~ "North America",
Source %in% Europe ~ "Europe",
Source %in% Asia ~ "Asia",
Source %in% Oceania ~ "Oceania",
Source %in% SouthAmerica ~ "South America",
Source %in% Others ~ "Rest of world"))

Create a map using Gapminder package data in R?

I am trying to create a map using the Gapminder package in R.
I have a basic map working, using the choroplethr package. But creating the map requires some data manipulation and the map and legend aren't particularly pretty looking. For example:
library(gapminder)
library(dplyr)
library(choroplethr)
# load data
data(gapminder, package = "gapminder")
# set up data for plot
plotdata <- gapminder %>%
filter(year == 2007) %>%
rename(
region = country,
value = lifeExp
) %>%
mutate(region = tolower(region)) %>%
mutate(region = recode(region,
"united states" = "united states of america",
"congo, dem. rep." = "democratic republic of the congo",
"congo, rep." = "republic of congo",
"korea, dem. rep." = "south korea",
"korea. rep." = "north korea",
"tanzania" = "united republic of tanzania",
"serbia" = "republic of serbia",
"slovak republic" = "slovakia",
"yemen, rep." = "yemen"
))
# make plot
country_choropleth(plotdata, legend = "life expectancy")
I was wondering if there are any other packages that could allow me to plot a map of the life expectancy using the Gapminder data from the Gapminder package?
Preferably, I would like to keep the data manipulation as minimal as possible (I need to demonstrate it to teenagers)... although I realise this may not be possible. Is there an easier way to plot this data on a map?
Any suggestions would be greatly appreciated.

Interactive Europe map R Shiny with ggmap

For a group project, I wanted to create a interactive Europe map, based on this data set: https://ourworldindata.org/causes-of-death.
I have manage to create this map, which will display the number of deaths caused by drowning in 2019 in Europe. But I would like to create an interactive map where the user could enter the cause of deaths for example HIV or Fire, so that the map could display it. I have tried to use an input but it doesn't work and shows me this error message : "Error in : Discrete value supplied to continuous scale". I know that the cause of this issue is the fact that the parameter size is a int but the input a char.
Unfortunalty I don't know how to correct this issue :(
Can anyone help me with it?
Have a nice day,
AM.
library("maptools")
library(rgdal)
library(maps)
library("jsonlite")
library(RColorBrewer)
library(ggmap)
rowdb <- read.csv("annual-number-of-deaths-by-cause.csv", sep = ';')
rowdb <- select(rowdb, -X.1, -X)
europe <- c(left = -12, bottom = 35, right = 30, top = 63)
map_E <- get_stamenmap(europe, zoom = 5,"toner-lite")
ggmap(map_E)
#On va cr?er une variable contenant les noms des pays du continent puis pour une date donn?e
#qu'on pourra aussi demander ? l'utilisateur de s?lectionner on affichera la carte du
#continent et la cause choisies
Europe_E <- c("Albania", "Andorra", "Armenia", "Austria","Azerbaijan","Belarus",
"Belgium", "Bosnia and Herzegovina", "Bulgaria", "Croatia","Cyprus",
"Czechia", "Denmark", "Estonia", "Finland", "France", "Georgia",
"Germany", "Greece", "Hungary", "Iceland", "Ireland", "Italy",
"Kazakhstan","Latvia", "Lithuania", "Luxembourg", "Malta", "Moldova", "Monaco",
"Montenegro", "Netherlands","North Macedonia", "Norway", "Poland", "Portugal",
"Romania", "Russia", "San Marino","Serbia", "Slovakia", "Slovenia", "Spain",
"Sweden", "Switzerland", "Turkey", "Ukraine", "United Kingdom")
#Fonction pour avoir la latitude et longitude des pays
if (!(require(jsonlite))) install.packages("jsonlite")
mygeocode <- function(adresses){
# adresses est un vecteur contenant toutes les adresses sous forme de chaine de caracteres
nominatim_osm <- function(address = NULL){
## details: http://wiki.openstreetmap.org/wiki/Nominatim
## fonction nominatim_osm propos?e par D.Kisler
if(suppressWarnings(is.null(address))) return(data.frame())
tryCatch(
d <- jsonlite::fromJSON(
gsub('\\#addr\\#', gsub('\\s+', '\\%20', address),
'http://nominatim.openstreetmap.org/search/#addr#?format=json&addressdetails=0&limit=1')
), error = function(c) return(data.frame())
)
if(length(d) == 0) return(data.frame())
return(c(as.numeric(d$lon), as.numeric(d$lat)))
}
tableau <- t(sapply(adresses,nominatim_osm))
colnames(tableau) <- c("lon","lat")
return(tableau)
}
latlon_E <- mygeocode(Europe_E)
#is(lalo)
dat_E <- as.data.frame(latlon_E)
DAT_E <- rowdb
DAT_E$Year <- year(as.Date(DAT_E$Year, format = "%Y"))
DAT_E <- DAT_E[
as.character(DAT_E$Year) %in% c("2019"), ]
DAT_E <- DAT_E[
DAT_E$Entity %in% Europe_E, ]
ggmap(map_E, extent = "device") +
geom_point(data = DAT_E, aes(x = dat_E$lon , y =dat_E$lat, color = Europe_E, size = Drowning), alpha = 0.5) +
geom_text(data = DAT_E, aes(x = dat_E$lon, y = dat_E$lat, label = Drowning), color = "black", size = 3.7) +
scale_size_continuous(range = c(6, 12)) + theme(legend.position = "none")+
facet_wrap(~ Year)

Warning in R maps

I am trying to map a bunch of countries with the following code.
require(mapdata)
# get the names
cc <- map('world', names = TRUE, plot = FALSE)
take <- unlist(sapply(c("iran", "malaysia", "saudi arabia", "united arab emirates", "kuwait", "bahrain", "indonesia", "qatar", "sudan", "pakistan", "bangladesh", "turkey", "egypt", "united kingdom", "jordan", "brunei", "sri lanka", "oman", "yemen", "lebanon", "kenya"), grep, tolower(cc), value = TRUE))
suppressWarnings(map())
suppressWarnings(map('world', regions=take, fill=TRUE, col='red', add = TRUE))
I get what I want, however, the Pdf version has the following warning printed on page
#### # maps v3.1: updated 'world': all lakes moved to separate new ### # 'lakes' database. Type '?world' or 'news(package="maps")'. #
I use suppressWarnings, but the warning is still printed. How can I hide this when I knit the document with knitr?

R, get longitude/latitude data for cities and add it to my dataframe [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I would like to get longitude/latitude data for the cities in my dataframe and add as 2 columns in my frame. I'm new to R and I do not know how to do it.
Could someone help me on this
My frame:
> data <- read.xlsx("example_city.xlsx", 1)
> data
City Country
1 Stockholm Sweden
2 Oslo Norway
3 Rome Italy
4 Rome Italy
5 Stockholm Sweden
6 Stockholm Sweden
7 Paris France
8 Paris France
9 Hamburg Germany
10 Paris France
11 Paris France
With reference to your original question https://stackoverflow.com/questions/20936263/use-ggplot2-to-plot-cities-on-a-map
# data
cities <- sort(c(rep('Stockholm', 3), 'Oslo', 'Rome', 'Rome', 'Paris', rep('Bonn',10), 'Paris', 'Paris', 'Stockholm'))
# get frequencies
freq <- as.data.frame(table(cities))
library(plotrix)
freq$Freq <- rescale(freq$Freq, c(1,10)) # c(scale_min, scale_max)
# get cities latitude/longitude - kindly provided by google:
library(ggmap)
lonlat <- geocode(unique(cities))
cities <- cbind(freq, lonlat)
# get matches between names {maps} names and EU country names
library(maps)
eu <- c("Austria", "Belgium", "Bulgaria", "Croatia", "Cyprus", "Czech Republic",
"Denmark", "Estonia", "Finland", "France", "Germany", "Greece",
"Hungary", "Ireland", "Italy", "Latvia", "Lithuania", "Luxembourg",
"Malta", "Netherlands", "Poland", "Portugal", "Romania", "Slovakia",
"Slovenia", "Spain", "Sweden", "United Kingdom")
warning("No matches in database for ", paste(setdiff(eu, map_data('world')$region), collapse=", "))
europe <- map_data('world', region=eu)
# plot
library(ggplot2)
ggplot(europe, aes(x=long, y=lat, group=group)) +
geom_polygon(fill="white", colour="black") +
xlim(-20, 40) + ylim(25,75) +
geom_point(data=cities, inherit.aes=F, aes(x=lon, y=lat, size=Freq), colour="red", alpha=.8) +
geom_text(data=cities, inherit.aes=F, aes(x=lon, y=lat, label=cities), vjust=1, colour="red", alpha=.5)

Resources