OK,這裏不使用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
[email protected]$count <- round(runif(nrow([email protected]), 0, 2500), 0)
[email protected]$count <- as.numeric([email protected]$count)
# and plot it
plot(uk, col = gray([email protected]$count/2500))
該代碼的結果如下圖。
編輯下面的請求,包括一個傳說,我已經調整了代碼一點點,但在所有誠實,我不明白基礎R的legend
功能也足以讓生產質量的東西,我沒有希望進一步研究。 (順便提一下,對於想法,請參考this question)。查看代碼下面的圖表表明我們需要對傳奇顏色等進行重新排序,但我會將其作爲練習留在原始海報中,或作爲另一個問題發佈。
# 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
[email protected]$count <- as.numeric(round(runif(nrow([email protected]), 0, 2500), 0))
[email protected]$bin <- cut([email protected]$count, seq(0, 2500, by = 250),
include.lowest = TRUE, dig.lab = 4)
# labels for the legend
lev = levels([email protected]$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'))
[email protected]$Col <- rbPal(10)[as.numeric(cut([email protected]$count, seq(0, 2500, by = 250)))]
# Plot
plot(uk, col = [email protected]$Col)
legend("topleft", fill = [email protected]$Col, legend = my.levels, col = [email protected]$Col)
真是太棒了,謝謝!你知道如何創建相應的圖例嗎? – userk
簡短的回答是'不是真的'。見上面編輯的答案。 – SlowLearner