在R语言中堆叠多图(Raster+高程线)并保持X轴尺度一致
解决R Markdown中栅格图与高程曲线X轴不一致的问题
这个问题我之前也碰到过——base R的plot.raster函数在R Markdown渲染环境中,有时候会忽略全局的par参数设置,自动调整轴的范围或样式,导致和下方的折线图X轴无法对齐。下面给你两种可行的解决方案:
方案一:调整Base R绘图的参数控制
通过手动关闭栅格图的自动轴绘制,强制统一X轴的尺度和对齐方式,同时调整边距避免重叠:
library(raster) library(rgdal) # 读取数据 T1_Domain <- raster("C:/Users/rm053078/Desktop/test1DEM.asc") T1_Section <- readOGR("C:/Users/rm053078/Desktop/Section.shp") T1_lat_profile <- extract(T1_Domain, T1_Section) # 设置布局、X轴对齐方式,同时调整边距 par(mfrow=c(2,1), xaxs = "i", mar = c(2, 4, 2, 2)) # 绘制栅格图:关闭自动轴,手动添加轴以保证尺度一致 plot(T1_Domain, ylab = "y", xlab = "", axes = FALSE, xlim = c(T1_Domain@extent@xmin, T1_Domain@extent@xmax)) axis(1) # 手动添加X轴 axis(2) # 手动添加Y轴 box() # 添加边框 points(400,50, pch = 4) text(400,50,labels = "1", pos = 4) points(600,50, pch = 4) text(600,50,labels = "1", pos = 4) # 调整下方图的边距,绘制高程曲线 par(mar = c(4, 4, 1, 2)) plot(x=seq(from = T1_Domain@extent@xmin, to = T1_Domain@extent@xmax, length.out = length(T1_lat_profile[[1]])), y=T1_lat_profile[[1]], type = "l", xlab = "x", ylab = "z", xlim = c(T1_Domain@extent@xmin, T1_Domain@extent@xmax), xaxs = "i")
关键修改点:
- 使用
axes=FALSE关闭栅格图的自动轴绘制,避免plot.raster自动调整轴范围 - 手动调用
axis()添加轴,保证X轴尺度和下方折线图完全一致 - 调整
mar参数设置边距,防止两个图的标签、轴重叠 - 在两个绘图中都明确指定
xaxs="i",确保X轴使用内部对齐(无额外空白)
方案二:使用ggplot2实现更稳定的渲染
如果想要在R Markdown中获得更一致的绘图效果,推荐使用ggplot2,它的布局系统不会轻易忽略尺度设置:
library(raster) library(rgdal) library(ggplot2) library(gridExtra) # 读取数据 T1_Domain <- raster("C:/Users/rm053078/Desktop/test1DEM.asc") T1_Section <- readOGR("C:/Users/rm053078/Desktop/Section.shp") T1_lat_profile <- extract(T1_Domain, T1_Section) # 转换栅格为ggplot可用的数据框 raster_df <- as.data.frame(T1_Domain, xy=TRUE) colnames(raster_df)[3] <- "elevation" # 构建高程曲线的数据框 profile_df <- data.frame( x = seq(from = T1_Domain@extent@xmin, to = T1_Domain@extent@xmax, length.out = length(T1_lat_profile[[1]])), z = T1_lat_profile[[1]] ) # 绘制栅格图 p1 <- ggplot(raster_df, aes(x=x, y=y)) + geom_raster(aes(fill=elevation)) + geom_point(aes(x=400, y=50), pch=4) + geom_text(aes(x=400, y=50, label="1"), hjust=0) + geom_point(aes(x=600, y=50), pch=4) + geom_text(aes(x=600, y=50, label="1"), hjust=0) + scale_x_continuous(limits = c(T1_Domain@extent@xmin, T1_Domain@extent@xmax), expand = c(0,0)) + scale_y_continuous(expand = c(0,0)) + labs(x="", y="y") + theme_bw() + theme(axis.title.x = element_blank()) # 绘制高程曲线 p2 <- ggplot(profile_df, aes(x=x, y=z)) + geom_line() + scale_x_continuous(limits = c(T1_Domain@extent@xmin, T1_Domain@extent@xmax), expand = c(0,0)) + labs(x="x", y="z") + theme_bw() # 组合两个图形 grid.arrange(p1, p2, nrow=2)
优势:
scale_x_continuous的expand=c(0,0)参数确保X轴完全贴合数据范围,和xaxs="i"效果一致- ggplot2在R Markdown中的渲染逻辑更稳定,不会出现base R中参数被覆盖的问题
- 图形样式更美观,可定制性更强
内容的提问来源于stack exchange,提问作者Ricardo
相关产品推荐
相关产品推荐

