问题
I'm trying to show some variogram model fits on the top of xy.plots. The panel.plots work for all except for a list of lines I wanted to add to corresponding subplots.
require(gstat)
require(sp)
data(meuse)
names(meuse)
#make directional variograms
b<-variogram(log(zinc)~1, meuse, alpha = c(0, 45, 90, 135))
#split the variogram data by direction
a<-lapply(1:length(unique(b$dir.hor)),
function(i) subset(b, grepl(unique(b$dir.hor)[[i]], b$dir.hor)))
#get the model fit parameters for each directional variogram
a<-lapply(1:length(unique(b$dir.hor)),
function(i) fit.variogram(a[[i]], vgm(0.5,"Exp", 1200, 0.5)))
#generate model data for the directional variograms
a<-lapply(1:length(a), function(i)
variogramLine(a[[i]], maxdist=1500))
#plot
require(lattice)
plot(b, ylim=c(0,1.2), xlim=c(0,1500), cex=1.5,
panel = function(x, y, ...) {panel.xyplot(x, y, ...)
panel.abline(v=1000, lwd=1, lty=3, col=2)
panel.lines(a[[i]], lwd=2, lty=2, col=4)
})
The last argument in the plot doesn't work because it's a list (see error on plot display), not sure how a list of lines should be plotted with lattice. Help will be appreciated!
回答1:
Use packet.number()
or panel.number()
to find the identity of the current panel. Your example was failing as it was so I imposed some changes to make it work properly.
library(gstat)
library(sp)
data(meuse)
# make directional variograms
b <- variogram(log(zinc) ~ x + y, meuse, alpha = c(0, 45, 90, 135))
# split the variogram data by direction
a <- lapply(1:length(unique(b$dir.hor)),
function(i) subset(b, grepl(unique(b$dir.hor)[[i]], b$dir.hor)))
# get the model fit parameters for each directional variogram
a <- lapply(1:length(unique(b$dir.hor)),
function(i) fit.variogram(a[[i]], vgm(0.5, "Exp", 1200, 0.5)))
# generate model data for the directional variograms
a <- lapply(1:length(a), function(i) variogramLine(a[[i]], maxdist = 1500))
# plot
require(lattice)
plot(b, ylim = c(0, 1.2), xlim = c(0, 1500), cex = 1.5,
panel = function(x, y, ...) {
panel.xyplot(x, y, ...)
panel.abline(v = 1000, lwd = 1, lty = 3, col = 2)
panel.lines(a[[packet.number()]], lwd = 2, lty = 2, col = 4)
})
来源:https://stackoverflow.com/questions/40826470/plot-a-list-of-lines-with-r-lattice-package