How to plot a heat map on a spatial map - r

I am new to spatial data analysis in R and would like to do something easy, I am still having difficulties...
I have a big table with latitudes and longitudes
sample = structure(list(Longitude = c(-0.19117, -0.211708, -0.206458,
-0.173862, -0.156618), Latitude = c(51.489096, 51.520075, 51.525301,
51.482442, 51.495752), Location_Easting_OSGR = c(525680L, 524170L,
524520L, 526900L, 528060L), Location_Northing_OSGR = c(178240L,
181650L, 182240L, 177530L, 179040L)), .Names = c("Longitude",
"Latitude", "Location_Easting_OSGR", "Location_Northing_OSGR"
), row.names = c(NA, -5L), class = c("data.table", "data.frame"
))
I got a map of the UK from GADM (level 2 of UK map).
I would like to be able to
plot points defined by longitude/latitude on the map
build a heat map that shows where the points are more concentrated...
Is it easy ? If not do you have some pointers (only UK please)
Cheers

Is this what you had in mind?
Your sample was too small to demonstrate a heat map, so I created a bigger sample with artificial clusters at (long,lat) = (-1,52), (-2,54) and (-4.5,56). IMO the map would be more informative without the points.
Also, I downloaded the shapefile, not the .Rdata, and imported that. The reason is that you are much more likely to find shapefiles in other projects, and it is easy to import them into R.
setwd("< directory with all your files>")
library(rgdal) # for readOGR(...)
library(ggplot2)
library(RColorBrewer) # for brewer.pal(...)
sample <- data.frame(Longitude=c(-1+rnorm(50,0,.5),-2+rnorm(50,0,0.5),-4.5+rnorm(50,0,.5)),
Latitude =c(52+rnorm(50,0,.5),54+rnorm(50,0,0.5),56+rnorm(50,0,.5)))
UKmap <- readOGR(dsn=".",layer="GBR_adm2")
map.df <- fortify(UKmap)
ggplot(sample, aes(x=Longitude, y=Latitude)) +
stat_density2d(aes(fill = ..level..), alpha=0.5, geom="polygon")+
geom_point(colour="red")+
geom_path(data=map.df,aes(x=long, y=lat,group=group), colour="grey50")+
scale_fill_gradientn(colours=rev(brewer.pal(7,"Spectral")))+
xlim(-10,+2.5) +
coord_fixed()
Explanation:
This approach uses the ggplot package, which allows you to create layers and then render the map. The calls do the following:
ggplot - establish `sample` as the default dataset and define (Longitude,Latitude) as (x,y)
stat_density2d - heat map layer; polygons with fill color based on relative frequency of points
geom_point - the points
geom_path - the map (boundaries of the admin regions)
scale_fill_gradientn - defines which colors to use for the fill
xlim - x-axis limits
coord_fixed - force aspect ratio = 1, so map is not distorted

Related

reduce number of points of a geometry of sf object in R

I am facing the following problem:
when using the shape file of intercommunal limits in France (which you can download here: https://www.data.gouv.fr/fr/datasets/r/971027a8-3ceb-48c6-97e3-59deaf7e2704), plotting the map is really slow:
library(sf)
library(ggplot2)
epci_france <- read_sf("./epci_shape/EPCI_SHAPEFILE.shp")
ggplot()+
geom_sf(data = test,
aes(geometry = geometry),
color = "black")+
guides(fill = "none")+
theme_void()
I think this is due to the high number of points in the shapefile.
Following comments in here: https://github.com/tidyverse/ggplot2/issues/2655, I tried
sum(rapply(st_geometry(epci_france), nrow))
[1] 1913182
which looks like a lot of points. I am looking for a way to lower this number, i.e. lower the precision of the limits of the geometry. I tried smooth from library(smoothr), but it has the opposite effect: it increases the number of points. I tried to cast it to other formats with st_cast, but it did not work either.
How should I proceed? My objective is to have a simple delimitation of the intercommunal limits to make choropleth maps. Thanks!

Map FAO fishing areas in R

I would like to make a map in R that colours in the FAO Fishing Areas according to a data set (in my case, length data of shark species).
I would prefer to do a choropleth map in ggplot but other types of maps are also fine. Worst case scenario a base map of FAO areas that I can add bubbles to. Even just an existing base map of FAO areas would be great. Any suggestions welcome!
I went to this page and clicked through to find this link to retrieve a GeoJSON file:
download.file("http://www.fao.org/fishery/geoserver/fifao/ows?service=WFS&request=GetFeature&version=1.0.0&typeName=fifao:FAO_AREAS_CWP&outputFormat=json", dest="FAO.json")
From here on, I was following this example from the R graph gallery, with a little help from this SO question and these notes:
library(geojsonio)
library(sp)
library(broom)
library(ggplot2)
library(dplyr) ## for joining values to map
spdf <- geojson_read("FAO.json", what = "sp")
At this point, plot(spdf) will bring up a plain (base-R) plot of the regions.
spdf_fortified <- tidy(spdf)
## make up some data to go with ...
fake_fish <- data.frame(id = as.character(1:324), value = rnorm(324))
spdf2 <- spdf_fortified %>% left_join(fake_fish, by = "id")
ggplot() +
geom_polygon(data = spdf2, aes( x = long, y = lat, group = group,
fill = value), color="grey") +
scale_fill_viridis_c() +
theme_void() +
theme(plot.background = element_rect(fill = 'lightgray', colour = NA)) +
coord_map() +
coord_sf(crs = "+proj=cea +lon_0=0 +lat_ts=45") ## Gall projection
ggsave("FAO.png")
notes
some of the steps are slow, it might be worth looking up how to coarsen/lower resolution of a spatial polygons object (if you just want to show the picture, the level of resolution might be overkill)
to be honest the default sequential colour scheme might be better but all the cool kids seem to like "viridis" these days so ...
There are probably better ways to do a lot of these pieces (e.g. set map projection, fill in background colour for land masses, ... ?)

How to overlay a heat map onto spatial map in R?

I am looking for help in creating a heat map of sorts that can overlay a spatial map. I have multiple data points, such as temperature, along coordinates in a river and would like to be able to visualize the change in temperature along the river (for example: higher temperature would be shown as red and lower temperature blue). Is this possible? I've gone through the different heat map questions and can't seem to piece it together.
This code gives the closest representation I think, but I don't know how to adapt it to what I need:
sample <- data.frame(Longitude=c(-1+rnorm(50,0,.5),-2+rnorm(50,0,0.5),-4.5+rnorm(50,0,.5)),
Latitude =c(52+rnorm(50,0,.5),54+rnorm(50,0,0.5),56+rnorm(50,0,.5)))
CanMap <- readOGR(dsn="gadm-CAN-shapefile",layer="gadm36_CAN_2")
map.df <- fortify(CanMap)
ggplot(sample, aes(x=Longitude, y=Latitude)) +
stat_density2d(aes(fill = ..level..), alpha=0.5, geom="polygon")+
geom_point(colour="red")+
geom_path(data=map.df,aes(x=long, y=lat,group=group), colour="grey50")+
scale_fill_gradientn(colours=rev(brewer.pal(7,"Spectral")))+
xlim(-10,+2.5) +
coord_fixed()

Heat Map in ggplot(), getting all the layers plotted

I am making a heat map of flooding incidents in the UK. I am following the example listed here. However, I am using a different base map from the example and it won't show up on the map. For my base map I use shapefiles provided by the UK gov, found here, and named it uk.shp, an sf object. Flooding data is proprietary and I cannot share but the original format is polygon shapefile. I then turn those shapefiles into gridded points so I can plot a continuous heat map, this sf object is named pt.shp.
Here is the the base map, original shapefile, and gridded points overlaid for context. You can see there are many floods here, often laying under the same point. I constructed a grid sf object that repeats a given point and uses flood ID as the unique identifier. Below is an example of the data with proprietary information removed. One possible issue I can think of is st_intersection returned the lat and long of the flooding shapefile (which I set as the mapping aes()) but the point's mapping coords are listed in the geometry column of the data.
However, when I use stat_density2d() with my base map, the continuous plot disappears. Below is my plotting code w/ each mapping iteration.
# base map plots
base <- ggplot()+
geom_sf(data=uk.shp)
# Plot density of the points
ggplot()+
stat_density2d(data=pt.shp, aes(x=long, y=lat, fill = ..density..), geom='tile', contour = F)
# base map shows up w/o density map? But legend exists so it is being mapped...
base +
stat_density2d(data=pt.shp, aes(x=long, y=lat, fill = ..density..), geom='tile', contour = F, alpha = .5) +
viridis::scale_fill_viridis(option='inferno')
Some issues are clear, like the plotting window of the heatmap has different dimensions than the base map. However, my main issues is I can't overlay the two plots and I don't know why.

Shading a map with underlying data in Julia

I want to create a map of Germany where each state is shaded according to its gross domestic product. I know how to do this in R (and put the code below). Is there a possibility to do this in Julia in an equally simple way?
library(tidyverse)
library(ggplot2)
library(sf)
shpData = st_read("./geofile.shp")
GDPData <- read.delim("./stateGDP.csv", header=FALSE)
GDPData <- rename(GDPData,StateName=V1,GDP=V2)
GDPData %>%
left_join(shpData) ->mergedData
ggplot(mergedData) + geom_sf(data = mergedData, aes(fill = BIP,geometry=geometry)) + coord_sf(crs = st_crs(mergedData))-> pBIP1
You'd load the Shapefile and use Plots to plot it.
The ideomatic code is something like
using Plots, Shapefile, CSV
shp = Shapefile.shapes(Shapefile.Table("geofile.shp"))
GDPData = CSV.read("stateGDP.csv")
plot(shp, fill_z = GDPData.V2')
Note the ' which transposes the values to a column vector - this will tell Plots to apply the colors to individual polygons.

Resources