[R-sig-Geo] how to specify the size of device so that it fits a SpatialPolygonsDataFrame plot exactly

Patrick Giraudoux p@tr|ck@g|r@udoux @end|ng |rom un|v-|comte@|r
Sat Jul 27 17:10:31 CEST 2019


Dear listers,

I would like to write jpeg (or png, etc.) maps using the function 
graphics:jpeg (png, etc.), but with the device window exactly fitting 
the map (= no white strip above, below or on the sides of the map). The 
map is derived from a SpatialPolygonsDataFrame (WGS84)

However, even if I set

par(mar=c(0,0,0,0) and pass xaxs='i', yaxs='i' in the plot, there are 
still white strips

I tried several tricks but none are fully satisfying.

Trial #1: I computed the ratio of the bounding box and using this ratio 
in the function jpeg with the height and width arguments. I did it both 
in WGS84 and in UTM47:

ratio<-(max(bbox(ChinaUTM)[1,])-min(bbox(ChinaUTM)[1,]))/(max(bbox(ChinaUTM)[2,])-min(bbox(ChinaUTM)[2,])) 
# ratio width/height

then

jpeg("./MapChina.jpeg",height=8,width=8*ratio,res=300,units="in")

par(mar=c(0,0,0,0)) # no margin
plot(China,col="grey",border="white",lwd=2,xaxs='i', yaxs='i')

dev.off()

The best is obtained with UTM47 (planar projection), however I get 
(almost) rid of any white strip only if I add an additionnal 1.04 
coefficient (obtained by trial-error)

Hence:

jpeg("./MapChina.jpeg",height=8,width=8*ratio*1.04,res=300,units="in")

par(mar=c(0,0,0,0)) # no margin
plot(China,col="grey",border="white",lwd=2,xaxs='i', yaxs='i')

dev.off()

Trial #2: The other way has been to pick up the parameter values like that:

par(mar=c(0,0,0,0)) # no margin
plot(China,col="grey",border="white",lwd=2,xaxs='i', yaxs='i')
pt<-par()$pin

ratio<-pt[2]/pt[1]

jpeg("./MapChina.jpeg",height=8,width=8*ratio,res=300,units="in")
par(mar=c(0,0,0,0)) # no margin
plot(China,col="grey",border="white",lwd=2,xaxs='i', yaxs='i') #

dev.off()

Does not work either

Any idea about how to deal with this ? In short how to get the exact 
size of a SpatialPolygonDataFrame plot to make the device window exactly 
this  size?

Best,

Patrick



More information about the R-sig-Geo mailing list