2016-04-06 45 views
1

我有这段代码,我创建了我的数据框的黄土表面。如何用ggplot绘制黄土表面

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(插值)列。谢谢。

回答

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() 

结果:

enter image description here

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")