如何使用tmap获取栅格地图的多变量构面(tm_raster()+ tm_facets())

时间:2019-01-29 21:35:33

标签: r r-raster tmap

我想使用tmap包使用我的栅格数据创建多面地图。 最终结果将是多个显示“值”的栅格地图,其中行显示“ class1”地图,列显示“ class2”地图,如下图所示:

enter image description here

我尝试了多种方法,但均未成功。我认为问题在于以正确的格式构建栅格砖层。不胜感激。

library(tmap)
library(dplyr)
library(magrittr)
library(raster)

r<-data.frame(lat=c(rep(12.25,5),rep(12.5,5)),
          lon=c(rep(c(-72.25,-71.75,-71.25,-70.25,-69.25),2)),
          value=runif(10));r
rx<-sp::SpatialPointsDataFrame(sp::SpatialPoints(coords= 
(cbind(r$lon,r$lat))),data=r%>%dplyr::select(value))
rx@data
sp::gridded(rx)<-T
rx<-raster(rx);rx
r
tm_shape(rx)+tm_raster()
# This works and shows one of the raster maps I would like.


m1<-r%>%dplyr::mutate(class1="class1_A",class2="class2_A",value=value*0.5)
m2<-r%>%dplyr::mutate(class1="class1_A",class2="class2_B",value=value*3)
m3<-r%>%dplyr::mutate(class1="class1_B",class2="class2_B",value=value*10)
m<-bind_rows(m1,m2,m3);m

mx<-sp::SpatialPointsDataFrame(sp::SpatialPoints(coords= 
(cbind(m$lon,m$lat))),data=m)
sp::gridded(mx)<-T
mx@data
# mx@data shows the data.frame with the lat/lon and the classes. 
# I would like to plot this as facets
mxr<-brick(mx)
tm_shape(mxr)+tm_raster(col="value")+tm_facets(by="class1","class2")

1 个答案:

答案 0 :(得分:0)

使用 ggplot2 代替 tmap 的答案:

library(dplyr)
library(ggplot2)

r <- data.frame(lat = c(rep(12.25, 5), rep(12.5, 5)),
                lon = c(rep(c(-72.25, -71.75, -71.25, -70.25, -69.25), 2)),
                value = runif(10))

m1 <- r %>% dplyr::mutate(class1 = "class1_A",
                      class2 = "class2_A",
                      value = value * 0.5)
m2 <- r %>% dplyr::mutate(class1 = "class1_A",
                      class2 = "class2_B",
                      value = value * 3)
m3 <- r %>% dplyr::mutate(class1 = "class1_B",
                      class2 = "class2_B",
                      value = value * 10)
m4 <- r %>% dplyr::mutate(class1 = "class1_B",
                          class2 = "class2_A",
                          value = value * 6)
m <- bind_rows(m1, m2, m3, m4)
head(m)
#>     lat    lon      value   class1   class2
#> 1 12.25 -72.25 0.07352787 class1_A class2_A
#> 2 12.25 -71.75 0.44638923 class1_A class2_A
#> 3 12.25 -71.25 0.20745736 class1_A class2_A
#> 4 12.25 -70.25 0.48200665 class1_A class2_A
#> 5 12.25 -69.25 0.06922203 class1_A class2_A
#> 6 12.50 -72.25 0.12036249 class1_A class2_A

# probably you should also add + coord_map()
ggplot(m, aes(x = lat, y = lon, fill = value)) + 
  geom_tile() +
  facet_grid(class1~class2) 

reprex package(v0.2.1)于2019-01-31创建