2

我有这段代码,我创建了我的数据框的黄土表面。

    library(gstat)
    library(sp)
    x<-c(0,55,105,165,270,65,130,155,155,225,250,295,
         30,100,110,135,160,190,230,300,30,70,105,170,
         210,245,300,0,85,175,300,15,60,90,90,140,210,
         260,270,295,5,55,55,90,100,140,190,255,285,270)
    y<-c(305,310,305,310,310,260,255,265,285,280,250,
         260,210,240,225,225,225,230,210,215,160,190,
         190,175,160,160,170,120,135,115,110,85,90,90,
         55,55,90,85,50,50,25,30,5,35,15,0,40,20,5,150)
    z<-c(870,793,755,690,800,800,730,728,710,780,804,
         855,813,762,765,740,765,760,790,820,855,812,
         773,812,827,805,840,890,820,873,875,873,865,
         841,862,908,855,850,882,910,940,915,890,880,
         870,880,960,890,860,830)

    dati<-data.frame(x,y,z)

    x.range <- as.numeric(c(min(x), max(x)))  
    y.range <- as.numeric(c(min(y), max(y)))

    meuse.loess <- loess(z ~ x * y, dati, degree=2, span = 0.25, 
                         normalize=F)
    meuse.mar <- list(x = seq(from = x.range[1], to = x.range[2], by = 1), y = seq(from = y.range[1], 
                                                                                    to = y.range[2], by = 1))
    meuse.lo <- predict(meuse.loess, newdata=expand.grid(meuse.mar), se=TRUE)

现在我想meuse.lo[[1]]用 ggplot2 函数绘图......但我不知道如何meuse.lo[[1]]在具有 x,y (网格坐标)和 z (插值)列的数据框中进行转换。谢谢。

4

2 回答 2

1

ggplot2可能不是 3d 图形的最佳选择。然而,这是一个简单的解决方案rgl

library(rgl)
plot3d(x, y, z, type="s", size=0.75, lit=FALSE,col="red")
surface3d(meuse.mar[[1]], meuse.mar[[2]], meuse.lo[[1]],
      alpha=0.4, front="lines", back="lines")
于 2016-04-06T09:54:50.290 回答
1

您的问题是,如果您用于生成新数据,则loess()返回一个矩阵。grid.expand()loess()

这在帮助中提到?loess.predict

如果 newdata 是调用 expand.grid 的结果,则预测(如果需要,还有 se)将是适当维度的数组。

现在,您仍然可以使用grid.expand()来计算新数据,但强制此函数返回数据框并删除属性。

来自?grid.expand

KEEP.OUT.ATTRS:应计算并返回指示“out.attrs”属性(见下文)的逻辑。

所以,试试这个:

nd <- expand.grid(meuse.mar, KEEP.OUT.ATTRS = FALSE)
meuse.lo <- predict(meuse.loess, newdata=nd, se=TRUE)

# Add the fitted data to the `nd` object
nd$z <- meuse.lo$fit

library(ggplot2)
ggplot(nd, aes(x, y, col = z)) + 
  geom_tile() +
  coord_fixed()

结果:

在此处输入图像描述

于 2016-04-06T09:56:31.973 回答