5
votes

I have an image and i want to plot only 100*100 square with left hand bottom corner at 0,0. when i use below commands. Why do i get a white space around my cropped image? how can i avoid it and ensure that I get exact 100*100 image?

If you want to repeat my example, you can use any image on line 1 (provided that the image is bigger than 100*100 pixels)

r <- raster("C:/Users/nnnn/Desktop/geo.jpg")
vector= getValues(r)
plot(r)
r


par(mar=c(0,0,0,0))
par(oma=c(0,0,0,0))
par(mai=c(0,0,0,0))
par(omi=c(0,0,0,0))
plot(r,xlim=c(0,100),ylim=c(0,100),legend=FALSE,axes=FALSE)

enter image description here

3
Do you want the image to maintain its aspect ratio (i.e. remain a square) even when you resize the window it's plotted in? Or are you asking about how to plot it to another non-interactive device (e.g. pdf, png, bmp, etc.) - Josh O'Brien
i want to save it as a square (cropped size) as a PNG file - user2543622
@JoshO'Brien would it be possible to provide suggestions regarding how I should change mar, mai, oma, omi options so that when i save the cropped image as png I don't get any white margins? - user2543622
I think your issue is that the default behaviour which "fills" the device, doesn't then respect the xlim/ylim for a given aspect ratio. I don't know an easy way, but judicious use of par(fig) can get you this. - mdsumner
@mdsumner would it be possible to suggest how i can use par(fig)? - user2543622

3 Answers

1
votes

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)
0
votes

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.)

enter image description here

-1
votes

Change the aspect ratio:

plot(r, asp=1)