题
我想做一个 levelplot
其中有一个背景图像。下面的代码提示错误信息 Error in rasterImage(image, x[1], y[1], x[length(x)], y[length(y)]) :
plot.new has not been called yet
- 显然 rasterImage
无法识别打印的 levelplot
对象作为绘图。什么是合适的方法而不是 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)])
解决方案
使用 +.trellis
和 layer
结合 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)
不隶属于 StackOverflow