R raster avoid white space when plotting

时间秒杀一切 提交于 2019-12-01 18:07:29

Aspect ratios are normally maintained for maps. You can use width/height when plotting to a file. You can resize the standard device manually, but you can also do this:

library(raster)
r <- raster(nrow=240, ncol=320)
values(r) <- 1:ncell(r)
dev.new(height=0.91*nrow(r)/50, width=1.09*ncol(r)/50)
plot(r, legend=FALSE)

Here's my best shot:

library(raster)

## An example raster
logo <- raster(system.file("external/rlogo.grd", package="raster")) 

## Clip out the lower-left 50*100 pixel rectangle as a new raster 'r'
cropWithRowCol <- function(r, rows, cols) {
    cc <- cellFromRowColCombine(r, rownr=rows, colnr=cols)
    crop(r, rasterFromCells(r, cc, values=FALSE))
}
r <- cropWithRowCol(logo, nrow(logo) - 49:0, 1:100)


## Extract multipliers used to appropriately size the selected device
w <- ncol(r)/max(dim(r))
h <- nrow(r)/max(dim(r))

## Set up appropriately sized device with no borders and required coordinate system    
## png("eg.png", width=480*w, height=480*h)
dev.new(width=5*w, height=5*h)
plot.new()
par(mar=c(0,0,0,0), oma=c(0,0,0,0))
plot.window(xlim=extent(r)[1:2], ylim=extent(r)[3:4], xaxs="i",yaxs="i")

## Finally, plot the (sub-)raster to it
plot(r, axes=FALSE, legend=FALSE, add=TRUE)
## dev.off()

(Please remember that, in an interactively resizable device, changing the device's size will mess up the plotted map's aspect ratio.)

Change the aspect ratio:

plot(r, asp=1)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!