Installing and activating all necessary packages.
#install.packages("rgeos",repos="http://R-Forge.R-project.org")
#install.packages("cartography")
#library("cartography")
#install.packages("broom")
packages=c("broom","devtools","sp","sf","raster","ggplot2","rgdal","cartography","ggiraph","rnaturalearth","readr","RCurl","htmlwidgets","hrbrthemes","colormap","widgetframe","dplyr","plotly","leaflet","ape","lubridate","tidyr","ggmap","RColorBrewer","dygraphs","xts")
lapply(packages, library, character.only=T)
Downloading and unzipping data:
#download.file("http://biogeo.ucdavis.edu/data/diva/adm/DEU_adm.zip", destfile = "./Data/DEU_adm.zip" , mode='wb')
#unzip("./Data/DEU_adm.zip", exdir = "./Data")
spcold=readOGR(dsn="./Data/DEU_adm2.shp",verbose=FALSE)
Picking html colors to plot the administrative districts of Germany:
spcold@data$COLOUR <- "#FFFFFF"
spcold@data$COLOUR[(as.numeric(as.character(spcold@data$ID_1)) %% 10) == 0] <- "#046837"
spcold@data$COLOUR[(as.numeric(as.character(spcold@data$ID_1)) %% 10) == 1] <- "#52BE79"
spcold@data$COLOUR[(as.numeric(as.character(spcold@data$ID_1)) %% 10) == 2] <- "#28B463"
spcold@data$COLOUR[(as.numeric(as.character(spcold@data$ID_1)) %% 10) == 3] <- "#F4EFDF"
spcold@data$COLOUR[(as.numeric(as.character(spcold@data$ID_1)) %% 10) == 4] <- "#138D75"
spcold@data$COLOUR[(as.numeric(as.character(spcold@data$ID_1)) %% 10) == 5] <- "#76D7C6"
spcold@data$COLOUR[(as.numeric(as.character(spcold@data$ID_1)) %% 10) == 6] <- "#A1E4D7"
spcold@data$COLOUR[(as.numeric(as.character(spcold@data$ID_1)) %% 10) == 7] <- "#D0ECE7"
spcold@data$COLOUR[(as.numeric(as.character(spcold@data$ID_1)) %% 10) == 8] <- "#FAE5D3"
spcold@data$COLOUR[(as.numeric(as.character(spcold@data$ID_1)) %% 10) == 9] <- "#E9CCE3"
plot(spcold, col=spcold$COLOUR, main = "Germany's administrative districts.")
The sf way looks like this:
sfcold <- st_read(dsn = "./Data/DEU_adm2.shp", quiet = TRUE)
class(sfcold)
## [1] "sf" "data.frame"
sfcold$COLOUR <- spcold@data$COLOUR
plot(st_geometry(sfcold), col=sfcold$COLOUR, main = "Germany's administrative districts.")
# Load data
data(nuts2006)
# Plot a layer with the extent of the EU28 countries with only a background color
plot(nuts0.spdf, border = NA, col = NA, bg = "#A6CAE0")
# Plot non european space
plot(world.spdf, col = "lightgreen", border=NA, add=TRUE)
# Plot a layer of countries borders
plot(nuts0.spdf, border = "grey20", lwd = 3, add = TRUE)
# Plot a layer of NUTS1
plot(nuts1.spdf, border = "grey30", lwd = 2, add = TRUE)
# Plot a layer of NUTS2
plot(nuts2.spdf, border = "grey40", lwd = 0.5, add = TRUE)
# Plot a layer of NUTS3
plot(nuts3.spdf, border = "grey20", lwd = 0.1, add = TRUE)
# Layout plot
layoutLayer(title = "Countries with the highest deaths in 2008", # title of the map
author = "Author: Schnepel (2018)", #
sources = "Sources: Please give credit", #
scale = NULL, # no scale
col = NA, # no color for the title box
coltitle = "black", # color of the title
frame = FALSE, # no frame around the map
bg = "#A6CAE0", # background of the map
extent = nuts0.spdf) # set the extent of the map
# Non European space
plot(world.spdf, col = "#AAB7B8", border = NA, add = TRUE)
# European (EU28) countries
plot(nuts0.spdf, col = "lightgreen",border = "black", lwd = 1, add = TRUE)
# Selection of the 10 most populated countries of Europe
dflab <- nuts0.df[order(nuts0.df$death_2008, decreasing = TRUE),][1:5,]
# Label creation
dflab$lab <- paste(dflab$id, "\n", round(dflab$death_2008/1000,0), "k", sep ="")
labelLayer(spdf = nuts0.spdf, # SpatialPolygonsDataFrame used to plot he labels
df = dflab, # data frame containing the lables
txt = "lab", # label field in df
col = "red", # color of the labels
cex = 0.6, # size of the labels
font = 3) # label font
# Add an explanation text
text(x = 5477360, y = 4177311, labels = "The 5 European countries
with the most deaths
in 2008 [thousands]", cex = 0.7, adj = 0)
# Compute the compound annual growth rate
nuts2.df$cagr <- (((nuts2.df$pop2008 / nuts2.df$pop1999)^(1/9)) - 1) * 100
# Set a custom color palette
cols <- carto.pal(pal1 = "green.pal", # first color gradient
n1 = 2, # number of colors in the first gradiant
pal2 = "red.pal", # second color gradient
n2 = 4) # number of colors in the second gradiant
# Plot a layer with the extent of the EU28 countries with only a background color
plot(nuts0.spdf, border = NA, col = NA, bg = "#A6CAE0")
# Plot non european space
plot(world.spdf, col = "#E3DEBF", border=NA, add=TRUE)
# Plot the compound annual growth rate
choroLayer(spdf = nuts2.spdf, # SpatialPolygonsDataFrame of the regions
df = nuts2.df, # data frame with compound annual growth rate
var = "cagr", # compound annual growth rate field in df
breaks = c(-2.43,-1,0,0.5,1,2,3.1), # list of breaks
col = cols, # colors
border = "grey40", # color of the polygons borders
lwd = 0.5, # width of the borders
legend.pos = "right", # position of the legend
legend.title.txt = "Compound Annual\nGrowth Rate", # title of the legend
legend.values.rnd = 2, # number of decimal in the legend values
add = TRUE) # add the layer to the current plot
# Plot a layer of countries borders
plot(nuts0.spdf,border = "grey20", lwd=0.75, add=TRUE)
# Layout plot
layoutLayer(title = "Demographic Trends", author = "cartography",
sources = "Eurostat, 2008", frame = TRUE, col = NA,
scale = NULL,coltitle = "black",
south = TRUE) # add a south arrow
Downloading data:
#download.file("http://thematicmapping.org/downloads/TM_WORLD_BORDERS-0.3.zip",
#destfile = "./Data/tm_world.zip" , mode='wb')
#unzip("./Data/tm_world.zip", exdir = "./datos")
### reading a shapefile
worldborder <- st_read("./Data/TM_WORLD_BORDERS-0.3.shp")
## Reading layer `TM_WORLD_BORDERS-0.3' from data source `/cloud/project/Geomatics/Data/TM_WORLD_BORDERS-0.3.shp' using driver `ESRI Shapefile'
## Simple feature collection with 246 features and 11 fields
## geometry type: MULTIPOLYGON
## dimension: XY
## bbox: xmin: -180 ymin: -90 xmax: 180 ymax: 83.6236
## epsg (SRID): 4326
## proj4string: +proj=longlat +datum=WGS84 +no_defs
seleurope = worldborder$REGION == 150 & worldborder$ISO3 != "RUS"
summary(seleurope)
## Mode FALSE TRUE
## logical 196 50
europefilter <- dplyr::filter(worldborder, seleurope)
popg <- read.csv("./Data/natural-population-growth.csv")#population growth
#unique(poverty_gap$Code)
head(popg)
npop <- filter(popg, Year==2015)#2015
names(npop) <- c("Entity", "Code", "Year", "Pop_Growth")
head(npop)
world <- sf::st_as_sf(rnaturalearth::countries110)
## str(world)
length(unique(world$iso_a3))
## [1] 175
nworldpop <- left_join(world, npop, by = c('iso_a3' = 'Code'))
nworldpop %>% st_transform(crs="+proj=laea +lon_0=18.984375")
head(nworldpop)
world.centerspop <- st_centroid(nworldpop)
world.spdfpop <- methods::as(nworldpop, 'Spatial')
world.spdfpop@data$id <- row.names(world.spdfpop@data)
world.tidypop <- broom::tidy(world.spdfpop)
world.tidypop <- dplyr::left_join(world.tidypop, world.spdfpop@data, by='id')
summary(world.tidypop$Pop_Growth)
## Min. 1st Qu. Median Mean 3rd Qu. Max. NA's
## -0.5702 0.3642 1.0433 1.1995 1.8440 4.0183 882
gpop <- ggplot(world.tidypop) +
geom_polygon_interactive(
color='gray18',
aes(long, lat, group=group, fill=(Pop_Growth),
tooltip=sprintf("%s<br/>%s",iso_a3,Pop_Growth))) +
hrbrthemes::theme_ipsum() +
colormap::scale_fill_colormap(
colormap=colormap::colormaps$autumn, reverse = T) +
labs(title='Global Natural Population Growth in 2015', subtitle='',
caption='Source: UN Population Division (2015)',
fill="Percent [%]")
gpop
The plotly package provides access to an online visualitation platform. Before running code in this section, you need to sign up at plotly[https://plot.ly/r/getting-started/]
df <- read.csv('https://raw.githubusercontent.com/plotly/datasets/master/2014_world_gdp_with_codes.csv')
# light grey boundaries
l <- list(color = toRGB("grey"), width = 0.5)
# specify map projection/options
g <- list(
showframe = FALSE,
showcoastlines = FALSE,
projection = list(type = 'Mercator')
)
p <- plot_geo(df) %>%
add_trace(
z = ~GDP..BILLIONS., color = ~GDP..BILLIONS., colors = 'Blues',
text = ~COUNTRY, locations = ~CODE, marker = list(line = l)
) %>%
colorbar(title = 'GDP Billions US$', tickprefix = '$') %>%
layout(
title = '2014 Global GDP<br>Source:<a href="https://www.cia.gov/library/publications/the-world-factbook/fields/2195.html">CIA World Factbook</a>',
geo = g
)
# Create a shareable link to your chart
# Set up API credentials: https://plot.ly/r/getting-started
chart_link = api_create(p, filename="nchoropleth-ag")
chart_link
#https://plot.ly/~gnarsk/1/
Ials’s interactive graph and data of “2014 Global GDPSource:CIA World Factbook” is a choropleth. The x-axis shows values from 0 to 0. The y-axis shows values from 0 to 0.
The following code is a just a plain visualization:
library(leaflet)
plt <- leaflet() %>%
setView(lat = 50.85045, lng = 4.34878, zoom=13) %>%
addTiles(group="OSM") %>%
addProviderTiles(providers$CartoDB.DarkMatter, group="Dark") %>%
addProviderTiles(providers$CartoDB.Positron, group="Light") %>%
addLayersControl(baseGroups=c('OSM','Dark','Light'))
plt
life <- read.csv("./Data/life-expectancy.csv")
head(life)
life15 <- filter(life, Year==2015)#
names(life15) <- c("Entity", "Code", "Year", "Life")
europelife <- left_join(europefilter, life15, by = c('ISO3' = 'Code'))
## Warning: Column `ISO3`/`Code` joining factors with different levels,
## coercing to character vector
europelife %>% st_transform(crs="+proj=laea +lat_0=52 +lon_0=10 +x_0=4321000 +y_0=3210000 +ellps=GRS80 +units=m +no_defs")
qpal <- colorNumeric("Blues", europelife$Life)
mlife<-leaflet(europelife)
mlife %>% addPolygons(
fillColor = ~qpal(Life),
weight = 2,
opacity = 1,
color = "black",
dashArray = "3",
fillOpacity = 0.7)%>%
leaflet::addLegend("bottomright", pal=qpal, values=europelife$Life,
title="Life expectancy [years]")%>%
leaflet::addScaleBar("bottomleft")
Life expectancy in Europe in 2015 (70 (darkred) to 85 (white) Years) ### 2.5.2 Creating an interactive map of europe showing the the share of population with alcohol disorders in 2016:
# Now, we'll create the Map
# This first command will creat an empty map
apal <- colorNumeric("PuOr", domain = a$Alc_2016)
malc<-leaflet(a)
malc %>%
addTiles()%>%
addCircleMarkers(
lng=~LON,
lat= ~LAT,
radius=~Alc_2016*4,
color = ~apal(Alc_2016),
stroke = FALSE, fillOpacity = 0.7,
#label=~as.character(Alc_2016),
labelOptions = labelOptions(noHide = T),
options = leafletOptions(minZoom = 0, maxZoom = 10,scroolWheelZoom=FALSE))%>%
leaflet::addLegend("bottomright",pal=apal,values=a$Alc_2016,title="Percent")
Reading in data and filtering:
measles <- read.csv("./Data/share-of-children-vaccinated-against-measles.csv")
names(measles) <- c("Entity", "Code", "Year", "measles")
europemeasles <- left_join(europefilter, measles, by = c('ISO3' = 'Code'))
## Warning: Column `ISO3`/`Code` joining factors with different levels,
## coercing to character vector
#europemeasles %>% st_transform(crs="+proj=laea +lat_0=52 +lon_0=10 +x_0=4321000 +y_0=3210000 +ellps=GRS80 +units=m +no_defs")
Split the data according to years:
meas80 <- filter(europemeasles, Year==1980)
meas90 <- filter(europemeasles, Year==1990)
meas2000 <- filter(europemeasles, Year==2000)
meas2010 <- filter(europemeasles, Year==2010)
Create a colour palette:
brew=brewer.pal(10,"Purples")
## Warning in brewer.pal(10, "Purples"): n too large, allowed maximum for palette Purples is 9
## Returning the palette you asked for with that many colors
mpal=colorBin(brew, europemeasles$measles, pretty = TRUE,
na.color = "#808080", alpha = FALSE, reverse = FALSE,
right = FALSE)
Creating the map with different years as layers:
basem<-leaflet()
leafletmap = basem %>% addTiles()%>%
addPolygons(data=testworldalc,fillColor = "darkgrey",weight = 2,opacity = 1,color = "black",
dashArray = "3",fillOpacity = 0.7,label = ~Entity)%>%
addPolygons(data=meas80,fillColor = ~mpal(measles),weight = 2,opacity = 1,color = "black",
dashArray = "3",group="1980",fillOpacity = 0.7,popup=paste("Currently",meas80$measles,"%"),label = ~Entity)%>%
addPolygons(data=meas90,fillColor = ~mpal(measles),weight = 2,opacity = 1,color = "black",
dashArray = "3",group="1990",fillOpacity = 0.7,popup=paste("Currently",meas90$measles,"%"),label = ~Entity)%>%
addPolygons(data=meas2000,fillColor = ~mpal(measles),weight = 2,opacity = 1,color = "black",
dashArray = "3",group="2000",fillOpacity = 0.7,popup=paste("Currently",meas2000$measles,"%"),label = ~Entity)%>%
addPolygons(data=meas2010,fillColor = ~mpal(measles),weight = 2,opacity = 1,color = "black",
dashArray = "3",group="2010",fillOpacity = 0.7,popup=paste("Currently",meas2010$measles,"%"),label = ~Entity)%>%
leaflet::addLegend("bottomright", pal=mpal, values=europelife$Life,
title="<p>Share of children</p><p>vaccinated against</p><p>measles in Europe[%]</p>")%>%
leaflet::addScaleBar("bottomleft")
leafletmap %>% addLayersControl(c("1980", "1990","2000","2010"),
options = layersControlOptions(collapsed = FALSE))