I have recently started coding with R, so far it has been quite a journey with several obstacles on the road. Most of them I have been able to solve by searching the internet. However, now I am encountering a problem I am unable to fix. I found a sort of similair thread on stackoverflow, (How to fill in the contour fully using stat_contour), nevertheless it does not work in my situation, ggmap + ggplot seem unable to work together.
So, the problem is the following. I am studying whether the red light district in Amsterdam has an effect on local businesses. I do this by creating plot that shows business density in the city centre of Amsterdam. I have used this code to make it:
# Background map
geo <- geocode("Amsterdam", source="google")
lon <- geo$lon - .000
lat <- geo$lat + .000
map <- get_map(c(lon = lon, lat = lat), zoom=14,maptype = "satellite", color="color")
p <- ggmap(map) + theme(legend.position = c(1, 1), legend.justification = c(1,1)) +
xlab("Longitude") + ylab("Latitude")
# Map boundaries
#xmin = 4.86774509503174
#xmax = 4.92267673565674
#ymin = 52.3534171572766
#ymax = 52.386956071714
# RLD Map (so it can be read by ggplot2)
rldmap <- fortify(rld)
rld2map <- fortify(rld2)
natmap <- fortify(nat)
# Ticks
mid <- 250
mi <- 0
ma <- 500
r <- (ma-mi)/5
breaks = seq(mi,ma,r)
# Density
ncells <- 150
dens2000 <- kde2d(bedrijven2000$LONG, bedrijven2000$LAT, n = ncells)
densdf2000 <- data.frame(expand.grid(x = dens2000$x, y = dens2000$y), z = as.vector(dens2000$z))
densmap2000 <- p + geom_point(aes(x = x, y = y), data = coords2000, alpha = .5, size = 1) +
stat_contour(aes(x,y,z=z,fill = ..level..), data=densdf2000,geom="polygon", alpha=.3, inherit.aes = F) +
scale_fill_gradientn(name="density", breaks = breaks, colours=rev(brewer.pal(7,"Spectral"))) +
geom_polygon(aes(x=long, y=lat, group=group), fill='grey', size=.2,color='green', data=rldmap, alpha=0) +
geom_polygon(aes(x=long, y=lat, group=group), fill='grey', size=.2,color='green', data=rld2map, alpha=0) +
geom_polygon(aes(x=long, y=lat, group=group), fill='grey', size=.2,color='green', data=natmap, alpha=0) +
geom_point(aes(x = x, y = y), data = coords,color = 'yellow',alpha = 1, size = 1, shape=10) +
annotate('text', x=4.892, y=52.374, label = "Amsterdam", col="white") +
ggtitle("Business Density in Amsterdam year=2000")
plot(densmap2000)
Using this code provides the following output: output density plot Amsterdam
The problem here is that the lines of the polygons that show the density stop when they are close to the border of the plot, this gives a disturbing image.
Therefore my question is, how can I make the polygons forget about the borders of the graph and make them continuous?