R - Plot will not add point data and will not plot grids - r

I have an image, and am trying to plot the number of quadrats that appear in each tessellated region.
I have two problems here:
My tessellated image will not plot with my gw_ppp points, even with an add = TRUE argument.
I am trying to plot the number of quadrants that appear inside each tessellated region, but the image is being plotted with zeros. Also, my gw_ppp points are not being plotted along with the image.
All of the files that can be used to reproduce the error can be found and downloaded in this Google Drive folder.
Here is what I have tried:
library(pacman)
p_load(spatstat,
dplyr,
maptools,
raster,
sf,
sp,
ggplot2)
#Set workplace directory to wherever you downloaded the files from:
setwd(C:\\Users\\Documents)
#Load all data, found in the link above
gw <- read.csv("RileyCNTYGWwells.csv", stringsAsFactors = FALSE)
elev <- raster('elevation.tif')
KS_counties <- st_read("KS_counties.shp")
#Select desired columns from .csv file
gw_sp <- gw %>%
dplyr::select(LONGITUDE, LATITUDE, WELL_USE, WELL_DEPTH, EST_YIELD) %>% na.omit(gw_sp)
#Convert to spatial dataframe
gw_cor <- st_as_sf(gw_sp, coords=c("LONGITUDE","LATITUDE"),
crs = st_crs(4326))
#Remove duplicated rows with dplyr's `distinct` function
gw_sp <- gw_cor %>%
distinct()
#Omit points outside Riley Co.
riley <- KS_counties %>%
filter(name == "Riley")
riley <- st_transform(riley, 4326)
gw_final <- st_intersection(riley, gw_sp)
#Project to a projected CRS, as spatstat is not happy with WGS84
utm14 <- '+proj=utm +zone=14 +ellps=GRS80 +to_meter=0.3048006096012192 +no_defs'
g <- st_transform(gw_final, crs = utm14)
#Filter unwanted columns
g <- g %>%
dplyr::select(WELL_USE:EST_YIELD)
#Finally, convert to ppp (RDS file)
gw_ppp <- as(g, "Spatial")
gw_ppp <- as(gw_ppp, "ppp")
From here, we can generate the quadrants:
#Generate the quadrat
q_well <- quadratcount(gw_ppp, nx = 10, ny = 10)
#Plot the quadrats and points
plot(gw_ppp, main = "Riley County Quadrat Well Count", cex = 0.5, pch = "+", cols = "red", legend = FALSE, use.marks = FALSE)
plot(q_well, add=TRUE, textargs = list(cex = 0.8))
These are the quadrant totals that need to show up on the graph (problem 2), but they are not being plotted.
Now, we will read in the elevation raster, reclassify it into 4 categories based on quantiles, and then plot the tessellation together with the gw_ppp points:
#Read in raster and mask to desired county shapefile
elev <- raster("elevation.tif")
riley <- st_transform(riley, crs(elev))
crop_riley <- crop(elev, riley)
mask_riley <- mask(crop_riley, mask = riley)
plot(mask_riley, main = "Riley County Elevation Map")
#Reclassify raster into quantiles
quantile(mask_riley)
elev_zones <- reclassify(mask_riley,
c(0, 361.6296, 1,
361.6296, 387.6583, 2,
387.6583, 403.2133, 3,
403.2133, 466.1521, 4))
elev_zones <- ratify(elev_zones)
plot(elev_zones, main = "Elevation Zones")
#Convert to a Spatstat-compatible object
elev_zones <- as.im.RasterLayer(elev_zones)
#Tesselate the image
tes <- tess(image = elev_zones)
plot(tes, main = "Tesselated Elevation Zones")
plot(gw_ppp, add=T, main = "Riley County Quadrat Well Count", cex = 1, pch = "+", cols = "black", legend = FALSE, use.marks = FALSE)
Problem 1 appears after the last line of code is run above. There are no gw_ppp points plotted.
Now, I'm trying to generate the number of quadrants that appear in each tessellated region:
q_elev <- quadratcount.ppp(gw_ppp, tess = tes)
plot(q_elev, main = "Riley County Quadrat Well Count")
plot(gw_ppp, add=T, cex = 1, pch = "+", cols = "black", legend = FALSE, use.marks = FALSE)
Result:
Here is problem 2. These values shouldn't be zeros, and the gw_ppp points are not showing. How can I fix these issues?

Related

Get relief of Switzerland from a shp-file

I would like an official source for drawing the relief over a map of Switzerland.
I downloaded https://cms.geo.admin.ch/ogd/topography/DHM25_BM_SHP.zip to use the dhm25_p.shp-File
Now using the code
aux <- st_read(dsn="dhm25_p.shp")
auxx <- as_Spatial(aux)
auxxx <- as.data.frame(auxx)
ggplot() +
# draw the relief
geom_raster(
data = auxxx,
inherit.aes = FALSE,
aes(
x = coords.x1,
y = coords.x2,
alpha = coords.x3
)
)
I'll get the error
Error in `geom_raster()`:
! Problem while converting geom to grob.
ℹ Error occurred in the 1st layer.
Caused by error:
! cannot allocate vector of size 6539542.5 Gb
A shapefile of points is generally not a good source for mapping continuous phenomena such as elevation. It is better to use raster data.
Here is a simple way to make an elevation map for Switzerland
library(terra)
library(geodata)
x <- geodata::elevation_30s("Switzerland", ".")
plot(x)
Add contour lines
v <- as.contour(x, levels=c(500,1000,3000))
lines(v)
Or show shaded relief
slope <- terrain(x, "slope", unit="radians")
aspect <- terrain(x, "aspect", unit="radians")
hill <- shade(slope, aspect, 40, 270)
plot(hill, col=gray(seq(0,1,.01)), legend=F, axes=F, mar=1)
To show relief and elevation
plot(hill, col=gray(seq(0,1,.01)), legend=F, axes=F)
plot(x, col=terrain.colors(25, alpha=.5), add=T, axes=F, legend=T)
You can do the same things with the Swiss government data from the website you point to in your (now hidden) answer. But it takes some more work if you want to remove the areas outside of Switzerland.
y <- rast("DHM200.asc")
# Assign the coordinate reference system (Landesvermessung 1903)
crs(y) <- "EPSG:21781"
# get the outline of the country and project it to the crs of the raster data
swz <- geodata::gadm("Switzerland", level=1, path=".")
pswz <- project(swz, y)
# remove values for areas outside of Switzerland
y <- mask(y, pswz)
plot(y)
lines (pswz)
And with ggplot you can use geom_spatraster
library(tidyterra)
library(ggplot2)
ggplot() + geom_spatraster(data = y)
For posterity, leveranging also on MPB_2022 and Robert, see how you can replicate the same map using ggplot2 + tidyterra (as explained in detail in https://dieghernan.github.io/202210_tidyterra-hillshade/):
library(terra)
library(geodata)
library(tidyterra)
library(ggplot2)
x <- geodata::elevation_30s("Switzerland", ".")
slope <- terrain(x, "slope", unit = "radians")
aspect <- terrain(x, "aspect", unit = "radians")
hill <- shade(slope, aspect, 40, 270)
# Hillshading, but we need a vector of colors
pal_greys <- hcl.colors(1000, "Grays")
# Get a vector of colors based on the value of shades
# Create index
hill_col <- hill %>%
# Rename layer
select(shades = 1) %>%
mutate(index_col = round(scales::rescale(shades, to = c(1, length(pal_greys))))) %>%
pull(index_col) %>%
pal_greys[.]
head(unique(hill_col), 10)
# Plot
ggplot() +
# Add our hill shade and use fill with the vector color
geom_spatraster(data = hill, fill = hill_col, maxcell = Inf, alpha = 1) +
# And add the initial raster with some alpha
geom_spatraster(data = x) +
# Add an hypstometric tint
scale_fill_hypso_tint_c(
palette = "dem_poster",
# Need alpha to show the hill
alpha = 0.5 ) +
theme_minimal() +
labs(fill="Elevation")

Formatting phylogeny to map projection (`phylo.to.plot`, or alternate method) in R

I am hoping someone can help me with the formating from phylo.to.plot() or suggest another method that can produce a similar output.
I have followed tutorial(s) here to produce an output but it seems difficult to alter the resulting figures.
Briefly these are my questions. I will expand further below.
How to plot a subregion of a "WorldHires" map, not entire region?
Change the shape of the points on the map, but maintain the colour?
Add gradient of continuous variable to map
Reproducible example:
Here is a very basic tree with some randomly assigned geographic locations
myTree <- ape::read.tree(text='((A, B), ((C, D), (E, F)));')
plot(myTree)
# It needs to be rooted for `phylo.to.map()` to work
myTree$branch.length = NULL
rooted_cladogram = ape::compute.brlen(myTree)
# Sample information
Sample <- c("A","B","C","D","E","F")
coords <- matrix(c(56.001966,57.069417,50.70228, 51.836213, 54.678997, 54.67831,-5.636926,-2.47805,-3.8975018, -2.235444,-3.4392211, -1.751833), nrow=6, ncol=2)
rownames(coords) <- Sample
head(coords)
## Plot phylo.to.map
obj<-phylo.to.map(rooted_cladogram,coords,database="worldHires", regions="UK",plot=FALSE,xlim=c(-11,3), ylim=c(49,59),direction="rightwards")
plot(obj,direction="rightwards",fsize=0.5,cex.points=c(0,1), lwd=c(3,1),ftype="i")
Plot output here:
Question 1: How do I plot a subregion of a "WorldHires" map, not the entire region?
I would like to only have mainland Britain which is a subregion of the "UK" in the WorldHires database. To access it normally I would do:
map1 <- ggplot2::map_data(map = "worldHires", region = c("UK"),xlim=c(-11,3), ylim=c(49,59))
GB <- subset(map1, subregion=="Great Britain")
# Plot
GB_plot<- ggplot(GB )+
geom_polygon(aes(x = long, y = lat, group = group), fill = "white", colour = "black")+
theme_classic()+
theme(axis.line=element_blank(),
axis.text=element_blank(),
axis.ticks=element_blank(),
axis.title=element_blank(),
panel.border = element_blank())
Which looks like this:
I have tried but it ignore the subregion argument.
obj<-phylo.to.map(ttree,coords,database="worldHires", regions="UK", subregion="Great Britain",plot=FALSE,xlim=c(-11,3), ylim=c(49,59),direction="rightwards")
Is there a way to provide it directly with a map instead of using WorldHires?
Question 2: How do I change the shape of the points on the map but keep maintain the colour?
I want to use shapes on the map to indicate the 3 major clade on my tree geographically. However, when I add a pch argument in, it correctly changes the shapes but the points then become black instead of following the colour that they were before. The lines from the tree to the map maintain the colour, it is just the points themselves that seem to turn black.
This is how I have tried to change the shape of the points:
# Original code - points
cols <-setNames(colorRampPalette(RColorBrewer::brewer.pal(n=6, name="Dark2"))(Ntip(myTree)),myTree$tip.label)
obj<-phylo.to.map(rooted_cladogram,coords,database="worldHires", regions="UK",plot=FALSE,xlim=c(-11,3), ylim=c(49,59),direction="rightwards")
plot(obj,direction="rightwards",fsize=0.5,cex.points=c(0,1), colors=cols,lwd=c(3,1),ftype="i")
Point and lines are coloured. I would like to change the shape of points
# Code to change points = but points are no longer coloured
shapes <- c(rep(2,2),rep(1,2),rep(0,2))
obj<-phylo.to.map(rooted_cladogram,coords,database="worldHires", regions="UK",plot=FALSE,xlim=c(-11,3), ylim=c(49,59),direction="rightwards")
plot(obj,direction="rightwards",fsize=0.5,cex.points=c(0,1), colors=cols,pch=shapes,lwd=c(3,1),ftype="i")
Output: The shapes are changed but they are no longer coloured in:
Question 3: How do I add a gradient to the map?
Given this fake dataset, how to I create a smoothed gradient of the value variable?
Any help and advice on this would be very much appreciated.
It would also be useful to know how to change the size of points
Thank you very much in advance,
Eve
I improved (somewhat) on my comments by using the map you made in your question. Here's the code:
library(mapdata)
library(phytools)
library(ggplot2)
myTree <- ape::read.tree(text='((A, B), ((C, D), (E, F)));')
plot(myTree)
# It needs to be rooted for `phylo.to.map()` to work
myTree$branch.length = NULL
rooted_cladogram = ape::compute.brlen(myTree)
# Sample information
Sample <- c("A","B","C","D","E","F")
coords <- matrix(
c(56.001966,
57.069417,
50.70228,
51.836213,
54.678997,
54.67831,
-5.636926,
-2.47805,
-3.8975018,
-2.235444,
-3.4392211,
-1.751833),
nrow=6,
ncol=2)
rownames(coords) <- Sample
head(coords)
obj <- phylo.to.map(
rooted_cladogram,
coords,
database="worldHires",
regions="UK",
plot=FALSE,
xlim=c(-11,3),
ylim=c(49,59),
direction="rightwards")
# Disable default map
obj2 <- obj
obj2$map$x <- obj$map$x[1]
obj2$map$y <- obj$map$y[1]
# Set plot parameters
cols <- setNames(
colorRampPalette(
RColorBrewer::brewer.pal(n=6, name="Dark2"))(Ntip(myTree)),myTree$tip.label)
shapes <- c(rep(2,2),rep(1,2),rep(0,2))
sizes <- c(1, 2, 3, 4, 5, 6)
# Plot phylomap
plot(
obj2,
direction="rightwards",
fsize=0.5,
cex.points=0,
colors=cols,
pch=shapes,
lwd=c(3,1),
ftype="i")
# Plot new map area that only includes GB
uk <- map_data(
map = "worldHires",
region = "UK")
gb <- uk[uk$subregion == "Great Britain",]
points(x = gb$long,
y = gb$lat,
cex = 0.001)
# Plot points on map
points(
x = coords[,2],
y = coords[,1],
pch = shapes,
col = cols,
cex = sizes)
e: Use sf object instead of points to illustrate GB. It is tough to provide more advice beyond this on how to add symbology for your spatially varying variable, but sf is popular and very well documented, e.g. https://r-spatial.github.io/sf/articles/sf5.html. Let me know if you have any other questions!
ee: Added lines to plot name and symbol on tips.
eee: Added gradient dataset to map.
library(phytools)
library(mapdata)
library(ggplot2)
library(sf)
myTree <- ape::read.tree(text='((A, B), ((C, D), (E, F)));')
plot(myTree)
# It needs to be rooted for `phylo.to.map()` to work
myTree$branch.length = NULL
rooted_cladogram = ape::compute.brlen(myTree)
# Sample information
Sample <- c("A","B","C","D","E","F")
coords <- matrix(c(56.001966,57.069417,50.70228, 51.836213, 54.678997, 54.67831,-5.636926,-2.47805,-3.8975018, -2.235444,-3.4392211, -1.751833), nrow=6, ncol=2)
rownames(coords) <- Sample
head(coords)
obj <- phylo.to.map(
rooted_cladogram,
coords,
database="worldHires",
regions="UK",
plot=FALSE,
xlim=c(-11,3),
ylim=c(49,59),
direction="rightwards")
# Disable default map
obj2 <- obj
obj2$map$x <- obj$map$x[1]
obj2$map$y <- obj$map$y[1]
## Plot tree portion of map
# Set plot parameters
cols <- setNames(
colorRampPalette(
RColorBrewer::brewer.pal(n=6, name="Dark2"))(Ntip(myTree)),myTree$tip.label)
shapes <- c(rep(2,2),rep(1,2),rep(0,2))
sizes <- c(1, 2, 3, 4, 5, 6)
# Plot phylomap
plot(
obj2,
direction="rightwards",
fsize=0.5,
cex.points=0,
colors=cols,
pch=shapes,
lwd=c(3,1),
ftype="i")
tiplabels(pch=shapes, col=cols, cex=0.7, offset = 0.2)
tiplabels(text=myTree$tip.label, col=cols, cex=0.7, bg = NA, frame = NA, offset = 0.2)
## Plot GB portion of map
# Plot new map area that only includes GB
uk <- map_data(map = "worldHires", region = "UK")
gb <- uk[uk$subregion == "Great Britain",]
# Convert GB to sf object
gb_sf <- st_as_sf(gb, coords = c("long", "lat"))
# Covert to polygon
gb_poly <- st_sf(
aggregate(
x = gb_sf$geometry,
by = list(gb_sf$region),
FUN = function(x){st_cast(st_combine(x), "POLYGON")}))
# Add polygon to map
plot(gb_poly, col = NA, add = TRUE)
## Load and format gradient data as sf object
# Load data
g <- read.csv("gradient_data.txt", sep = " ", na.strings = c("NA", " "))
# Check for, then remove NAs
table(is.na(g))
g2 <- g[!is.na(g$Lng),]
# For demonstration purposes, make dataset easier to manage
# Delete this sampling line to use the full dataset
g2 <- g2[sample(1:nrow(g2), size = 1000),]
# Create sf point object
gpt <- st_as_sf(g2, coords = c("Lng", "Lat"))
## Set symbology and plot
# Cut data into 5 groups based on "value"
groups <- cut(gpt$value,
breaks = seq(min(gpt$value), max(gpt$value), len = 5),
include.lowest = TRUE)
# Set colors
gpt$colors <- colorRampPalette(c("yellow", "red"))(5)[groups]
# Plot
plot(gpt$geometry, pch = 16, col = gpt$colors, add = TRUE)
## Optional legend for gradient data
# Order labels and colors for the legend
lev <- levels(groups)
# Used rev() here to make colors in correct order
fil <- rev(levels(as.factor(gpt$colors)))
legend("topright", legend = lev, fill = fil, add = TRUE)
## Plot sample points on GB
# Plot points on map
points(
x = coords[,2],
y = coords[,1],
pch = shapes,
col = cols,
cex = sizes)
see here for more info on gradient symbology and legends: R: Gradient plot on a shapefile

Origin destination plot

I am looking for a way to add more information to this Origin-Destinatio plot. First i would like to add a label to each of the zones (origin/ destination). Secondly, I would also like to plot a map as a background and possibly add a color gradient to the plot.
Example datasets are included in the package stplanR. I use a different dataset.
This is my code so far:
library(stplanr)
library(tidyverse)
library(sp)
Cents <- read.table(...)
str(Cents)
head(Cents)
coords <- Cents[,c("lat","lon")]
data <- as.data.frame( Cents[,1])
crs <- CRS("+init=epsg:28992") # proj4string of coords
Centssp <- SpatialPointsDataFrame(coords = coords,
data = data,
proj4string = crs)
Flows <- read.table(...)
l <- od2line(flow = Flows, zones = Centssp)
l
plot(l, lwd = l$MotorisedTraffic / 5)`
Thanks in advance!
edit: code with example datasets
l <- od2line(flow = flow, zones = cents)
l
# remove lines with no length
plot(l, lwd = l$All / 5 )```
To add a map to the background, try
plot(l, lwd = l$All / 5 )
plot(map, add=T) #add this for a map

Plotting polygons with rasters in base R, ggplot2 or levelplot

I am trying to plot in R a raster layer with lines/polygon objects in R and each time I fail miserably with errors. I tried to do this in base R, ggplot2 and using levelplot but can't get the right result.
Source data can be found here.
What I need to do in the plot (all in one plot) is to:
1) zoom in a certain area defined as NIG. T
2) Display raster r values on a scale with cuts intervals.
3) Plot the country boundaries(shpAfr in base R and ggplot2 or world.outlines.spin levelplot). 4) Finally, include shpWater polygon layer (with col="blue" fill and contours).
library(raster)
library(maptools)
library(rasterVis)
library(viridis)
library(sf)
library(rgdal)
library(ggplot2)
r <- raster("raster_example.tif")
crs(r) <- "+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +to wgs84=0,0,0"
NIG <- c(2,14.5,4,14)
Reg_name <- "Nigeria"
shpAfr <- readOGR(dsn="Africa.shp")
proj4string(shpAfr) # describes data’s current coordinate reference system
#st_read(system.file("shape/nc.shp", package="sf"))
# Import water polygon
shpWater <- readOGR(dsn="waterbodies_africa.shp")
shpWater.count <- nrow(shpWater#data)
shpWater$id <- 1:shpWater.count
shpWater.fort <- fortify(shpWater, region='id')
# Import Africa admin map
shpAfr <- readOGR(dsn="Africa.shp")
shpAfr.count <- nrow(shpAfr#data)
shpAfr$id <- 1:shpAfr.count
shpAfr.fort <- fortify(shpAfr, region='id')
# Set colour intervals for plotting:
cuts=seq(0,1,0.1) #set breaks
Trying in base R, my problem is I can get the water shape fill in the right colour (fill and contour should be blue). If I try to plot both wrld_simpl and shpWater as polygon() I get into even bigger troubles.
plot(r, xlim = NIG[1:2], ylim = NIG[3:4],
breaks=cuts, col = rev(plasma(11)))
lines(wrld_simpl,lwd = 1.5)
lines(shpWater, col="blue") # works but cannot fill the polygon
polygon(shpWater, col = "blue", border = "blue") # getting error here
Error in as.double(y) :
cannot coerce type 'S4' to vector of type 'double'
Ok, so now I try ggplot2, but I can't find a way to include a raster here without getting an error.
lon <- seq(r#extent#xmin,r#extent#xmax,
(r#extent#xmax-r#extent#xmin)/r#ncols)
lat <- seq(r#extent#ymin,r#extent#ymax,
(r#extent#ymax-r#extent#ymin)/r#nrows)
Plot1 <- ggplot()+
geom_polygon(aes(x = long, y = lat, group=id),
data = shpAfr.fort, color ="grey27", fill ="grey",
alpha = .4, size = .2)+
geom_raster(data = test, aes(fill=values))+ ## here it goes bad
#geom_tile(data=test_df, aes(x=x, y=y, fill=value), alpha=0.8) +
#scale_fill_viridis() +
geom_polygon(aes(x = long, y = lat, group=id),
data = shpWater.fort, color ="lightskyblue2", fill ="lightskyblue2",
size = .2)+coord_equal()+
theme_minimal()+
coord_map(xlim = Region[[3]][1:2],ylim = Region[[3]][3:4])
plot(Plot1)
Finally, I tried the levelplot and AGAIN failed.
mapTheme <- rasterTheme(region = rev(brewer.pal(10, "RdBu")))
# Get world outlines:
world.outlines <- map("world", plot=FALSE)
world.outlines.sp <- map2SpatialLines(world.outlines, proj4string = CRS("+proj=longlat"))
# Plot raster and polygon:
Plot2 <- levelplot(r,par.settings = mapTheme,pretty=TRUE,margin = F,
xlim = NIG[1:2],ylim = NIG[3:4],
col.regions=colorRampPalette(c("light blue","blue", "red")),
main=paste0("test")) + layer(sp.lines(world.outlines.sp, col = "black", lwd = 0.5))
plot(Plot2 + layer(sp.lines(world.outlines.sp, col = "black", lwd = 0.5))
#Error: Attempted to create layer with no stat.
My results so far:
1) first image does not have the polygons filled with blue
2) second image has clearly world outlines not in the right location
:
You would have probably have had answers a lot earlier if you had made a simple reprex, e.g. like this
library(raster)
r <- raster(res=1/12)
values(r) <- sample(100, ncell(r), replace=TRUE)
filename <- system.file("external/lux.shp", package="raster")
v <- shapefile(filename)
zoom in a certain area
One way to zoom is to use crop (alternatively use the ext argument in plot)
x <- crop(r, v)
Display raster r values on a scale with cuts intervals
cuts <- c(0,20,60,100)
plot(x, breaks=cuts, col=rainbow(3))
or
y <- cut(x, cuts)
Plot the country boundaries
lines(v)
Finally, include polygon layer (with col="blue" fill and contours).
plot(v[c(1,3),], col="blue", border="red", lwd=2, add=TRUE)
6 months later but I feel this question. My two thoughts are (1) I have had luck with plotting geom_sf and geom_stars together. You have to change your raster to a df before changing to a geom_stars. and (2) regardless of method, you need all datasets in the same projection - check with crs() and set all to the same with st_transform()
I didn't actually test this with your data but something like:
make raster into a df
test.df = as.data.frame (test, xy=TRUE) # Convert to data.frame, keeping the
coordinates
class(test.df)
convert to geom_stars
test.stars = st_as_stars(test.df)
try your plot
Plot1 <- ggplot()+
geom_stars(data = test, aes(fill=values))+ #need to plot raster first I think?
scale_fill_identity( name = "", breaks = cuts,labels = "")+
geom_sf(data = shpAfr.fort, color ="grey27", size = .2)+
geom_sf(data = shpWater.fort, color ="lightskyblue2", fill
="lightskyblue2", size = .2)+
theme_minimal()+
coord_sf( xlim = NIG[1:2], ylim = NIG[3:4]),expand = FALSE)
Plot1

How to add a column with location-based data to a SpatialPolygonsDataFrame in R?

I have spatial data in R which is loaded as a SpatialPolygonsDataFrame:
library(sp)
library(tmap)
d <- readRDS("data.rds")
qtm(d)
For the example, I used data for Germany from http://www.gadm.org/download.
Below, you see the map plotted by qtm(d). However, I would like to display my own data. I have locations with longitude and lattitude, and I would like to count the number of points inside the mapped polygons and show those counts as the color of the map below.
I have no clue where to start. Is there a simple approach that maps locations to the polygons?
I'm not very experienced with spatial data, however, maybe you can use this as a starter:
library(sp)
library(raster)
library(rgeos)
# load map
d <- getData("GADM", country = "Germany", level = 2)
# generate some random points
set.seed(1)
p <- data.frame(
lon = jitter(sample(8:13, 20, T)),
lat = jitter(sample(49:52, 20, T))
)
# match points with polygons
mat <- gContains(d, SpatialPoints(p, proj4string=CRS(sp::proj4string(d))), byid=TRUE)
hits <- colSums(mat)
cols <- rev(heat.colors(diff(range(hits))+1))
# plot
plot(d, col = cols[hits+1], border = "green")
with(p, points(lon, lat, col = "blue", pch = 19, cex = .5))

Resources