我有这个代码,我创建了我的数据帧的黄土表面。
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)
现在我想用ggplot2函数绘制meuse.lo[[1]]
...但我不知道如何在数据框中转换meuse.lo[[1]]
x,y(网格坐标)和z(插值)列。感谢。
答案 0 :(得分: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")
答案 1 :(得分:1)
此处的问题是loess()
如果您使用grid.expand()
生成loess()
的新数据,则会返回矩阵。
?loess.predict
的帮助中提到了这一点:
如果newdata是对expand.grid的调用的结果,那么预测(以及s.e。如果请求的话)将是一个适当维度的数组。
现在,您仍然可以使用grid.expand()
来计算新数据,但强制此函数返回数据框并删除属性。
来自?grid.expand
:
KEEP.OUT.ATTRS:表示&#34; out.attrs&#34;应计算并返回属性(见下文)。
所以,试试这个:
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()
结果: