Site icon R-bloggers

Plot 3D Topographic Map in R

[This article was first published on Chen-ang Statistics » R, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

As we all know, there are a lot of packages provide functions to plot maps, such as ggmap, GEOmap, rworldmap and so on. For visualizing 2D topographic map, here is a good example. Besides, 3D topographic map is also easily to be plotted via some excellent functions and packages. The implement methods include but are not limited to the following three approaches: persp(), wireframe() in lattice and rgl.surface() in rgl. Furthermore, the last way of these can  output an interactive graphics.

1 function persp

persp()  is a generic function which enables user to  draw perspective plots of a surface over the x–y plane. Please view the following example, and the data were simulated by bivariate normal distribution.

library(mvtnorm);
library(MASS);
set.seed(5)
sigma <-matrix(c(4,2,2,3), ncol=2)
x<-rmvnorm(n=500, mean=c(1,2), sigma=sigma,
method="chol")
z<-kde2d(x[,1],x[,2],n=200);
par(mar=rep(0,4))
persp(z,theta=60,phi=5,col=heat.colors(199,alpha=1),
shade=0.4,border=NA,box=FALSE)

Additionally, it is worth mentioning that although the graph is static, users still are able to let it be interactive via function getGraphicsEvent().(code)

2 package lattice

In package lattice, wireframe() is also a generic function which can draw 3d scatter plots and surfaces. We take the dataset from package marmap for instance.

library(marmap);
library(lattice);
data(nw.atlantic);
atl<-nw.atlantic;
atl<-as.bathy(atl);
wireframe(unclass(atl),shade=T,aspect=c(1/2,0.1),
xlab="",ylab="",zlab="",scales=list(draw=F,arrows=FALSE));

There are more details in the reference manual of package lattice.

3 package rgl

Package rgl provides medium to high level functions for 3D interactive graphics and actually the result is really perfect. We consider the dataset volcano for example and the following graph is just a screenshot of the output.

library(rgl);
data(volcano);
z<-3*volcano;
x<-10*(1:nrow(z));
y<-10*(1:ncol(z));
zlim<-range(z);
zlen<-zlim[2]-zlim[1]+1;
colorlut<-terrain.colors(zlen,alpha=0);
col<-colorlut[z-zlim[1]+1];
open3d();
rgl.surface(x,y,z,color=col,alpha=1,back="lines");
#add the contour map in different color
colorlut <- heat.colors(zlen,alpha=1);
col<-colorlut[z-zlim[1]+1];
rgl.surface(x,y,matrix(1,nrow(z),ncol(z)),color=col,back="fill");

 

 

 

To leave a comment for the author, please follow the link and comment on their blog: Chen-ang Statistics » R.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.