1
我想在美國和加拿大填色網格單元格。我的目標與這個問題非常相似:R Plot Filled Longitude-Latitude Grid Cells on Map但是,這個問題只涉及美國,我無法弄清楚如何添加加拿大。美國和加拿大的彩色網格單元格
我能夠通過修改代碼來繪製地圖,美國和加拿大在這裏找到:https://groups.google.com/forum/#!topic/ggplot2/KAKhoE0GO4U
library(ggplot2)
library(rgeos)
library(maps)
library(maptools)
PolygonCoords <- function(polygon) {
polygons <- [email protected]
coords.list <- lapply(seq_along(polygons), function(i) {
# Extract the group, sequence, area, longitude, and latitude.
coords <- polygons[[i]]@coords
cbind(i, 1:nrow(coords), polygons[[i]]@area, coords)
})
coords.df <- as.data.frame(do.call(rbind, coords.list))
names(coords.df) <- c("order", "seq", "area", "long", "lat")
return(coords.df)
}
ConvertWorldSimple <- function(mapdata, min.area = 0) {
coords.list <- lapply([email protected], PolygonCoords)
ncoords <- sapply(coords.list, nrow)
coords.df <- do.call(rbind, coords.list)
coords.df$country <- rep([email protected]$NAME, ncoords)
country.group <- factor(paste(coords.df$country, coords.df$order))
coords.df$group <- as.numeric(country.group)
coords.df <- coords.df[coords.df$area >= min.area, ]
return(coords.df)
}
data("wrld_simpl")
world <- ConvertWorldSimple(wrld_simpl, min.area = 0.1)
world <- world[world$country %in% c('United States', 'Canada'),]
na <- data.frame(
country = c("United States", "Canada"),
is.north.america = TRUE)
world <- merge(world, na, all.x = TRUE)
world$is.north.america[is.na(world$is.north.america)] <- FALSE
world <- world[order(world$order, world$seq), ]
ggplot(world, aes(long, lat, group = group)) +
geom_polygon(aes(fill = is.north.america)) +
geom_path(color = "white", size = 0.1) +
scale_fill_manual(values = c("darkgray"), guide = "none") +
scale_y_continuous("", breaks=(-2:2) * 30) +
scale_x_continuous("", breaks=(-4:4) * 45) +
coord_equal() +
theme_bw()
下面是代碼來創建網格單元假屬性數據,發現這裏:http://www.numbertheory.nl/2011/11/08/drawing-polar-centered-spatial-maps-using-ggplot2/
set.seed(1234)
xlim = c(-110,-100)
ylim = c(40,60)
dat_grid = expand.grid(x = xlim[1]:xlim[2], y = ylim[1]:ylim[2])
dat_grid$z = runif(nrow(dat_grid))
head(dat_grid)
這裏是在前面的堆棧溢出後用於覆蓋屬性的網格地圖的48個對ggplot2
代碼:
library(ggplot2)
library(maps)
us_states <- map_data("state")
(ggplot(aes(x=x,y=y,fill=z),data=dat_grid) + geom_tile())+geom_polygon(data=us_states,aes(x=long, y=lat, group=group), colour="black", fill="white", alpha=0)
如何結合兩個ggplot
語句將假屬性數據網格覆蓋到美國和加拿大的地圖上?感謝您的任何建議。
這一直是非常有幫助的。我討厭再問一次。雖然,如果地圖可以集中在大陸將是理想的。 –
這很容易,最後'+ xlim(175,320)+ ylim(20,90)'' –