简体   繁体   English

从数据绘制 3D 表面

[英]Plotting a 3D surface from data

I have written C++ code to numerically solve a PDE.我已经编写了 C++ 代码来数值求解 PDE。 I would like to plot the result.我想绘制结果。 I have outputted the data to an ascii file, as 3 columns of numbers.我已将数据作为 3 列数字输出到 ascii 文件。 The x-coordinate, the y-coordinate and the z-coordinate. x 坐标、y 坐标和 z 坐标。 This might look like这可能看起来像

0.01 7 -3
-12 1.2 -0.24
...

I often have in excess of 1000 data points.我经常有超过 1000 个数据点。 I want to plot a surface.我想绘制一个曲面。 I was able to load the data in both R and octave.我能够在 R 和八度中加载数据。 In R scatterplot3D worked, and in octave plot3 worked.在 R scatterplot3D 中工作,在八度 plot3 中工作。 However, I wish to produce a surface, and not distinct points (scatterplot3d), or a curve (plot3).但是,我希望生成一个曲面,而不是不同的点 (scatterplot3d) 或曲线 (plot3)。 I am struggling to get mesh or surf to work from data in octave.我正在努力让网格或冲浪从八度音程的数据中工作。 I am looking for a simple way to plot a surface in 3D space with octave, R, C++ or any other program.我正在寻找一种简单的方法来使用八度音程、R、C++ 或任何其他程序在 3D 空间中绘制曲面。

You could coerce the data into the correct format for plotting with the base R function persp .您可以将数据强制转换为正确的格式,以便使用基本 R 函数persp进行绘图。 This requires a vector of unique x values, a vector of unique y values, and a matrix of z values which is a length(unique(x)) by length(unique(y)) matrix.这需要一个唯一 x 值向量、一个唯一 y 值向量和一个 z 值矩阵,它是一个length(unique(x))length(unique(y))矩阵。

Suppose your data looks like this:假设您的数据如下所示:

x    <- y <- seq(-pi, pi, length = 20)
df   <- expand.grid(x = x, y = y)
df$z <- cos(df$x) + sin(df$y)

head(df)
#>           x         y           z
#> 1 -3.141593 -3.141593 -1.00000000
#> 2 -2.810899 -3.141593 -0.94581724
#> 3 -2.480205 -3.141593 -0.78914051
#> 4 -2.149511 -3.141593 -0.54694816
#> 5 -1.818817 -3.141593 -0.24548549
#> 6 -1.488123 -3.141593  0.08257935

Then you can create a matrix like this:然后你可以创建一个这样的矩阵:

z <- tapply(df$z, list(df$x, df$y), mean)

So your plot would look like this:所以你的情节看起来像这样:

persp(unique(df$x), unique(df$y), z, 
      col = "gold", theta = 45, shade = 0.75, ltheta = 90)

If your x and y co-ordinates are not nicely aligned, then a more general approach would be:如果您的 x 和 y 坐标没有很好地对齐,那么更通用的方法是:

z <- tapply(df$z, list(cut(df$x, 20), cut(df$y, 20)), mean, na.rm = TRUE)

persp(as.numeric(factor(levels(cut(df$x, 20)), levels(cut(df$x, 20)))), 
      as.numeric(factor(levels(cut(df$y, 20)), levels(cut(df$y, 20)))), 
      z, col = "gold", theta = 45, shade = 0.75, ltheta = 90, xlab = "x", 
      ylab = "y")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM