好的,这是一个不使用的替代解决方案ggplot
(我将留下该ggplot
解决方案以供参考)。这段代码很简单,但应该足以让您了解如何将其适应您自己的数据。
# UK shapefile found via http://www.gadm.org/download
uk.url <- "http://www.filefactory.com/file/s3dz3jt3vr/n/GBR_adm_zip"
# replace following with your working directory - no trailing slash
work.dir <- "C:/Temp/r.temp/gb_map"
# the full file path for storing file
file.loc <- paste0(work.dir, "/uk.zip")
download.file (uk.url, destfile = file.loc, mode = "wb")
unzip(file.loc, exdir = work.dir)
# open the shapefile
require(rgdal)
uk <- readOGR(work.dir, layer = "GBR_adm2")
# make some fake data to plot
uk@data$count <- round(runif(nrow(uk@data), 0, 2500), 0)
uk@data$count <- as.numeric(uk@data$count)
# and plot it
plot(uk, col = gray(uk@data$count/2500))
代码的结果如下图。
在请求包含图例后进行编辑,我对代码进行了一些调整,但老实说,我对 base R 的legend
功能还不够了解,无法获得生产质量的东西,我不想进一步研究它。(顺便提一下这个问题的提示。)查看代码下方的图表明我们需要重新排序图例颜色等,但我会将其留给原始海报作为练习或作为另一个问题发布。
# UK shapefile found via http://www.gadm.org/download
uk.url <- "http://www.filefactory.com/file/s3dz3jt3vr/n/GBR_adm_zip"
# replace following with your working directory - no trailing slash
work.dir <- "C:/Temp/r.temp/gb_map"
# the full file path for storing file
file.loc <- paste0(work.dir, "/uk.zip")
download.file (uk.url, destfile = file.loc, mode = "wb")
unzip(file.loc, exdir = work.dir)
# open the shapefile
require(rgdal)
uk <- readOGR(work.dir, layer = "GBR_adm2")
# make some fake data to plot
uk@data$count <- as.numeric(round(runif(nrow(uk@data), 0, 2500), 0))
uk@data$bin <- cut(uk@data$count, seq(0, 2500, by = 250),
include.lowest = TRUE, dig.lab = 4)
# labels for the legend
lev = levels(uk@data$bin)
lev2 <- gsub("\\,", " to ", lev)
lev3 <- gsub("\\]$", "", lev2)
lev4 <- gsub("\\(|\\)", " ", lev3)
lev5 <- gsub("^\\[", " ", lev4)
my.levels <- lev5
# Create a function to generate a continuous color palette
rbPal <- colorRampPalette(c('red','blue'))
uk@data$Col <- rbPal(10)[as.numeric(cut(uk@data$count, seq(0, 2500, by = 250)))]
# Plot
plot(uk, col = uk@data$Col)
legend("topleft", fill = uk@data$Col, legend = my.levels, col = uk@data$Col)