Adding a background image to a levelplot

我们两清 提交于 2019-12-11 19:45:10

问题


I'd like to make a levelplot which has a background image. The following code promts the error message Error in rasterImage(image, x[1], y[1], x[length(x)], y[length(y)]) : plot.new has not been called yet - apparently rasterImage does not recognize printed levelplot object as a plot. What's the appropriate method instead of rasterImage?

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

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

meshstep <- 0.2
x<- seq(-20,20,meshstep)
y <-seq(-20,20,meshstep)

image <- readPNG("imagepath\\image.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.3)


plot(p)
rasterImage(image, x[1], y[1],x[length(x)],y[length(y)])

回答1:


Use +.trellis and layer combined with grid.raster:

library(grid)
library(latticeExtra)
library(png)

image <- readPNG(system.file("img", "Rlogo.png", package="png"))

p + layer(grid.raster(as.raster(image)), under=TRUE) 


来源:https://stackoverflow.com/questions/20054383/adding-a-background-image-to-a-levelplot

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