我想繪製一幅美國地圖,然後填寫海洋圖。如何在美國的地圖上爲海洋藍色着色?
這裏是我的出發點:
library(maps)
library(graphics)
image(x=-90:-75, y = 25:40, z = outer(1:15, 1:15, "+"),
xlab = "lon", ylab = "lat")
map("state", add = TRUE)
但我想墨西哥的大西洋和墨西哥灣的純色填充。
我想繪製一幅美國地圖,然後填寫海洋圖。如何在美國的地圖上爲海洋藍色着色?
這裏是我的出發點:
library(maps)
library(graphics)
image(x=-90:-75, y = 25:40, z = outer(1:15, 1:15, "+"),
xlab = "lon", ylab = "lat")
map("state", add = TRUE)
但我想墨西哥的大西洋和墨西哥灣的純色填充。
好問題!這個怎麼樣?
library(maps)
image(x=-90:-75, y = 25:40, z = outer(1:15, 1:15, "+"),
xlab = "lon", ylab = "lat")
map("state", add = TRUE)
library(grid)
outline <- map("usa", plot=FALSE) # returns a list of x/y coords
xrange <- range(outline$x, na.rm=TRUE) # get bounding box
yrange <- range(outline$y, na.rm=TRUE)
xbox <- xrange + c(-2, 2)
ybox <- yrange + c(-2, 2)
# create the grid path in the current device
polypath(c(outline$x, NA, c(xbox, rev(xbox))),
c(outline$y, NA, rep(ybox, each=2)),
col="light blue", rule="evenodd")
閱讀保羅的Murrell的(背後的男人grid
)網格路徑(pdf here)最近的R-雜誌的文章後,我整個解決這個問題就來了。
記住:
「這不是你畫什麼,這是什麼,你不畫」 - 保羅馬雷爾
+1不錯的解決方案。 – 2013-05-02 09:07:23
+1爲您的來源提供全部功勞。 – 2013-05-02 11:48:18
這裏的一個變種(R雜誌卷4/2)。解決方案通過相交/差分多邊形完成工作。數據集wrld_simpl
可以被任何其他SpatialPolygons *對象替換。
library(maptools)
library(raster)
library(rgeos)
data(wrld_simpl)
x <- list(x=-90:-75, y = 25:40, z = outer(1:15, 1:15, "+"))
## use raster to quickly generate the polymask
## (but also use image2Grid to handle corner coordinates)
r <- raster(image2Grid(x))
p <- as(extent(r), "SpatialPolygons")
wmap <- gIntersection(wrld_simpl, p)
oceanmap <- gDifference(p, wmap)
image(r)
plot(oceanmap, add = TRUE, col = "light blue")
(地圖數據轉換到這可能是艱難的,我是不會輕易與maptools::map2SpatialPolygons
做到這一點,它會採取一些變通方法)
我可以回答你的問題的標題( 「我怎樣才能在美國的地圖上染上藍色的海洋?」),儘管不是在你的問題的主體中描述的具體情況(「我想畫一幅美國的地圖 ,然後填寫海洋「)。
但是,如果對其他遇到您的問題的人有幫助,我將包含此答案。
map(database='state', bg='light blue')
的bg
選項提供的淡藍色到地圖的背景,其中包括海洋的顏色。
它可能會更容易從藍色背景開始,然後掩蓋圖像/熱圖上的狀態邊界。 – 2013-05-02 00:48:21
或者有一個單獨的海洋多邊形(我認爲'rgeos'有一個差異函數,如果你還沒有這樣一個多邊形)。 – 2013-05-02 01:35:14