为了方便复制,请参考以下数据:
但是这样会导致一些密度方块被绘制在伦敦之外:
library(rgdal)
library(ggplot2)
library(rgeos)
download.file("http://spatialanalysis.co.uk/wp-content/uploads/2010/09/London_Sport.zip",
destfile = "London_Sport.zip")
unzip("London_Sport.zip")
projection="+proj=merc"
london_shape = readOGR("./", layer="london_sport")
# Create random points
set.seed(1)
points = data.frame(long=rnorm(10000, mean=-0.1, sd=0.1), lat=rnorm(10000, mean=51.5, sd=0.1))
points = SpatialPoints(points, proj4string=CRS("+proj=latlon"))
# Transform data to our projection
london = spTransform(london_shape, CRS(projection))
points = spTransform(points, CRS(projection))
# Keeps only points inside London
intersection = gIntersects(points, london, byid = T)
outside = apply(intersection == FALSE, MARGIN = 2, all)
points = points[which(!outside), ]
# Blank theme
new_theme_empty <- theme_bw()
new_theme_empty$line <- element_blank()
new_theme_empty$rect <- element_blank()
new_theme_empty$strip.text <- element_blank()
new_theme_empty$axis.text <- element_blank()
new_theme_empty$plot.title <- element_blank()
new_theme_empty$axis.title <- element_blank()
new_theme_empty$plot.margin <- structure(c(0, 0, -1, -1), unit = "lines", valid.unit = 3L, class = "unit")
# Prepare data to ggplot
london = fortify(london)
points = as.data.frame(points)
我希望绘制一个点密度图。这可以通过使用stat_bin2d
来实现:
ggplot() +
geom_polygon(data=london, aes(x=long,y=lat,group=group), fill="black") +
stat_bin2d(data=points, aes(x=long,y=lat), bins=40) +
geom_path(data=london, aes(x=long,y=lat,group=id), colour='white') +
coord_equal() +
new_theme_empty
但是这样会导致一些密度方块被绘制在伦敦之外:
gDifference
函数。一如既往,如果您提供一个小的可重现示例以说明您的进展情况,那么将有助于其他人的理解。 - Andy W