如何创建3D-MATLAB样式-R中的曲面图
我发现在R中创建美学上令人愉悦的3D曲面具有挑战性.我熟悉解决方案(persp
,image
,wireframe
,lattice
,rgl
以及其他一些其他问题中的解决方案SO),但结果并不理想.
I find it challenging to create aesthetically pleasing 3D surfaces in R. I am familiar with the solutions (persp
, image
, wireframe
, lattice
, rgl
and several other solutions in other questions in SO), but the results are not nice.
是否可以像在MATLAB中那样在R中创建3D表面图?
Is it possible to create 3D surface plots in R like in MATLAB?
Here is the MATLAB code
% Create a grid of x and y points
points = linspace(-2, 0, 20);
[X, Y] = meshgrid(points, -points);
% Define the function Z = f(X,Y)
Z = 2./exp((X-.5).^2+Y.^2)-2./exp((X+.5).^2+Y.^2);
% "phong" lighting is good for curved, interpolated surfaces. "gouraud"
% is also good for curved surfaces
surf(X, Y, Z); view(30, 30);
shading interp;
light;
lighting phong;
title('lighting phong', 'FontName', 'Courier', 'FontSize', 14);
剧情是现代的,丰富多彩的,美学上令人愉悦的,代码语法也很可读.
The plot is modern, colorful, aesthetically pleasing, the code syntax is very readable.
在基数R中有可能吗?
jet.colors
是对一种Matlab调色板的R-答案:
jet.colors
is the R-answer to one of hte Matlab color palettes:
points = seq(-2, 0, length=20)
#create a grid
XY = expand.grid(X=points,Y=-points)
# A z-function
Zf <- function(X,Y){
2./exp((X-.5)^2+Y^2)-2./exp((X+.5)^2+Y^2);
}
# populate a surface
Z <- Zf(XY$X, XY$Y)
zlim <- range(Z)
zlen <- zlim[2] - zlim[1] + 1
jet.colors <- # function from grDevices package
colorRampPalette(c("#00007F", "blue", "#007FFF", "cyan",
"#7FFF7F", "yellow", "#FF7F00", "red", "#7F0000"))
colorzjet <- jet.colors(100) # 100 separate color
require(rgl)
open3d()
rgl.surface(x=points, y=matrix(Z,20),
coords=c(1,3,2),z=-points,
color=colorzjet[ findInterval(Z, seq(min(Z), max(Z), length=100))] )
axes3d()
rgl.snapshot("copyMatlabstyle.png")
我要承认,使颜色与"Z轴"(实际上是rgl y轴)对齐是很不直观的.如果您希望Matlab提供的闪亮镜面效果可以在照明角度下发挥.
I will admit that getting the colors to line up with the "Z-axis" (which is actually the rgl y-axis) seemed very unintuitive. If you want the shiny, specular effect that Matlab delivers you can play with the angle of illumination.
您还可以添加或删除照明:
You can also add or remove lighting:
clear3d(type = "lights")
light3d(theta=0, phi=0)
light3d(theta=0, phi=0) # twice as much light.
之后:
grid3d("x")
grid3d("y")
grid3d("z")
rgl.snapshot("copyMatlabstyle3.png")
您可以使用以下方法将y网格放置在表面后面":
You could have put the y-grid "behind" the surface with:
grid3d("y+")
对axes3d
或axis3d
调用的类似调整可能会移动秤的位置.
Similar tweaks to the axes3d
or axis3d
calls could move the location of the scales.
有关其他示例,请参见 http://rgm3.lab. nig.ac.jp/RGM/R_image_list 并搜索"plot3d",其中显示了看一下Karline Soetaert的plot3D软件包插图,R2BayesX::plot3d
函数的示例,
For further examples, look at http://rgm3.lab.nig.ac.jp/RGM/R_image_list and search for 'plot3d' which brings up examples of the Look at Karline Soetaert's plot3D package vignette, "50 ways to plot a volcano"R2BayesX::plot3d
function,