You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在R中使用levelplot为多幅栅格图创建共享图例

R中levelplot多栅格图共享图例的实现问题

我正在使用R的levelplot函数绘制三幅栅格图像,希望为这些图像添加共享图例。虽然通过stack合并栅格可以实现共享图例,但该方法无法为每个子图添加单独文本,还可能破坏轴标签和刻度,因此想寻找更高效的替代方案。我尝试了三种方法,均未得到理想结果:


方法1:stack合并栅格后绘制(结果不符合预期)

s <- stack(raster_layer1, raster_layer2, raster_layer3)

color_range <- colorRampPalette(c("aliceblue","cadetblue1", "deepskyblue3","darkblue"))
my_colors <- color_range(9)
my.at <- c(seq(0,240,by=30),Inf)
my.brks <- c(seq(0,240,by=30),Inf,cex=2)
myColorkey <- list(at=my.at, labels=c("0","100","200","300","400","500","600","700","800","Inf"))

levelplot(s, col.regions=my_colors, at=my.at, colorkey=myColorkey,
          margin=F,
          cex.main =0.3,line = 0.5,  scales = list(x = list(cex = 1), y = list(cex = 1)),
          xlab = list("longitude (°E) ",fontface = "bold"), ylab =list("latitude (°N)",fontface = "bold"))

方法2:分别绘制后排列(每个子图都带图例)

one <- levelplot(raster_layer1, col.regions=my_colors, at=my.at, colorkey=myColorkey,
          margin=F,
          cex.main =0.3,line = 0.5,  scales = list(x = list(cex = 1), y = list(cex = 1)),
          xlab = list("longitude (°E) ",fontface = "bold"), ylab =list("latitude (°N)",fontface = "bold"))

two <- levelplot(raster_layer2, col.regions=my_colors, at=my.at, colorkey=myColorkey,
               margin=F,
               cex.main =0.3,line = 0.5,  scales = list(x = list(cex = 1), y = list(cex = 1)),
               xlab = list("longitude (°E) ",fontface = "bold"), ylab =list("latitude (°N)",fontface = "bold"))

three <- levelplot(raster_layer3, col.regions=my_colors, at=my.at, colorkey=myColorkey,
               margin=F,
               cex.main =0.3,line = 0.5,  scales = list(x = list(cex = 1), y = list(cex = 1)),
               xlab = list("longitude (°E) ",fontface = "bold"), ylab =list("latitude (°N)",fontface = "bold"))

post <- grid.arrange(one,two,three,ncol=3)

方法3:draw.colorkey添加共享图例(颜色显示异常)

k <- draw.colorkey(myColorkey)
post <- grid.arrange(one,two,three,k,ncol=4)

栅格数据生成代码

raster_layer1 <- raster(matrix(runif(100 *100, min = 50, max = 800), nrow = 100, ncol = 100), 
                      xmn = 0, xmx = 10, ymn = 0, ymx = 10)
raster_layer2 <- raster(matrix(runif(100 *100, min = 50, max = 500), nrow = 100, ncol = 100), 
                      xmn = 0, xmx = 10, ymn = 0, ymx = 10)
raster_layer3 <- raster(matrix(runif(100 *100, min = 50, max = 300), nrow = 100, ncol = 100), 
                      xmn = 0, xmx = 10, ymn = 0, ymx = 10)

内容的提问来源于stack exchange,提问作者CovetTachi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 09:12:41