在 R 中绘制 3D 数据 [英] Plot 3D data in R
问题描述
我有一个 3D 数据集:
I have a 3D dataset:
data = data.frame(
x = rep( c(0.1, 0.2, 0.3, 0.4, 0.5), each=5),
y = rep( c(1, 2, 3, 4, 5), 5)
)
data$z = runif(
25,
min = (data$x*data$y - 0.1 * (data$x*data$y)),
max = (data$x*data$y + 0.1 * (data$x*data$y))
)
data
str(data)
我想绘制它,但是 R alwyas 的内置函数给出了错误
And I want to plot it, but the built-in-functions of R alwyas give the error
增加 'x' 和 'y' 值
increasing 'x' and 'y' values expected
# ### 3D Plots ######################################################
# built-in function always give the error
# "increasing 'x' and 'y' values expected"
demo(image)
image(x = data$x, y = data$y, z = data$z)
demo(persp)
persp(data$x,data$y,data$z)
contour(data$x,data$y,data$z)
当我在互联网上搜索时,我发现当 X 和 Y 值的组合不唯一时会出现此消息.但在这里,它们是独一无二的.
When I searched on the internet, I found that this message happens when combinations of X and Y values are not unique. But here they are unique.
我尝试了其他一些库,在那里它可以正常工作.但是我不喜欢绘图的默认样式(内置函数应该可以满足我的期望).
I tried some other libraries and there it works without problems. But I don't like the default style of the plots (the built-in functions should fulfill my expectations).
# ### 3D Scatterplot ######################################################
# Nice plots without surface maps?
install.packages("scatterplot3d", dependencies = TRUE)
library(scatterplot3d)
scatterplot3d(x = data$x, y = data$y, z = data$z)
# ### 3D Scatterplot ######################################################
# Only to play around?
install.packages("rgl", dependencies = TRUE)
library(rgl)
plot3d(x = data$x, y = data$y, z = data$z)
lines3d(x = data$x, y = data$y, z = data$z)
surface3d(x = data$x, y = data$y, z = data$z)
为什么内置函数不接受我的数据集?
Why are my datasets not accepted by the built-in functions?
推荐答案
如果您正在处理网格间隔和序列不能保证增加或唯一的真实"数据(希望 (x,y,z)
组合至少是唯一的,即使这些三元组是重复的),我建议使用 akima
包从不规则网格插入到规则网格.
If you're working with "real" data for which the grid intervals and sequence cannot be guaranteed to be increasing or unique (hopefully the (x,y,z)
combinations are unique at least, even if these triples are duplicated), I would recommend the akima
package for interpolating from an irregular grid to a regular one.
使用您对data
的定义:
library(akima)
im <- with(data,interp(x,y,z))
with(im,image(x,y,z))
这不仅适用于 image
,也适用于类似的功能.
And this should work not only with image
but similar functions as well.
请注意,akima::interp
将数据映射到的默认网格由跨越 x
和 y 范围的 40 个相等间隔定义
值:
Note that the default grid to which your data is mapped to by akima::interp
is defined by 40 equal intervals spanning the range of x
and y
values:
> formals(akima::interp)[c("xo","yo")]
$xo
seq(min(x), max(x), length = 40)
$yo
seq(min(y), max(y), length = 40)
当然,这可以通过将参数 xo
和 yo
传递给 akima::interp
来覆盖.
But of course, this can be overridden by passing arguments xo
and yo
to akima::interp
.
这篇关于在 R 中绘制 3D 数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!