Ответ 1
Это то, что вы имели в виду?
Ваш sample
был слишком мал, чтобы продемонстрировать карту тепла, поэтому я создал более крупный образец с искусственными кластерами в (long, lat) = (-1,52), (-2,54) и (-4,5, 56). ИМО карта будет более информативной без точек.
Кроме того, я загрузил шейп файл, а не .Rdata и импортировал его. Причина в том, что вы гораздо чаще находите шейп файлы в других проектах, и их легко импортировать в 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()
Объяснение:
В этом подходе используется пакет ggplot
, который позволяет создавать слои, а затем отображать карту. Вызовы выполняют следующие действия:
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