0

As a follow-up on Adding a background image to a levelplot I'm exporting the levelplot to a png file, and I'd like to know how I can access the width and height of that trellis object to pass it as parameters to png.

library("png")
library("lattice")
library("latticeExtra")

MyFunction <- function(x,y){
  return(
    dnorm(sqrt(x^2+y^2)))}

meshstep <- 0.2
x<- seq(-30,30,meshstep)
y <-seq(-20,20,meshstep)
image <- readPNG(system.file("img", "Rlogo.png", package="png"))

grid <- expand.grid(x=x, y=y)

grid$z<- MyFunction(grid$x,grid$y)

MyPalette <- colorRampPalette(c('white','yellow', 'red'))

levels <- 10
p<- levelplot(z~x*y, grid, cuts = levels, xlab="",
                ylab="",
                colorkey = TRUE, region = TRUE,col.regions=MyPalette(levels+1),
                alpha.regions=0.5) 
+ layer(grid.raster(as.raster(image)), under=TRUE) 

trellis.device(device="png", filename="MWE.png")
print(p)
dev.off()

For the resulting png file, the width and height are 480px, since this is the default. I'd like to write trellis.device(device="png", filename="MWE.png", width=width(p), height=height(p)) or something similar to keep the x and y axes evenly spaced.

Community
  • 1
  • 1
Roland
  • 517
  • 8
  • 25

1 Answers1

0

The height and width of a lattice plot are the dimensions of the graphics device in use. So I think you should just set the size of your png device here.

 png(width=500, height=700) 
 p ## your plot command here
 dev.off()
agstudy
  • 119,832
  • 17
  • 199
  • 261
  • But how do I set them up in a way that the x and y axis are displayed with the same scale? Think of a Map as background image - I don't want to have different scalings in x and y. I'd like to do this as a command depending on the plot, not on some manually set parameters. – Roland Nov 22 '13 at 00:10