How to plot a 3D surface of a 3D matrix with R - r

I have 3D matrix of floating point numbers and I would like to produce a smoothed 3D surface of this matrix using R. Any suggestions are welcome. Thanks
Now I am using scatterplot3d ... But this function did not produce a smoothed surface
x<-read.table("/Users/me/Desktop/data.txt")
scatterplot3d(x$V1, x$V2, x$V3, highlight.3d = TRUE, angle = 30, col.axis = "blue", col.grid = "lightblue", cex.axis = 1.3, cex.lab = 1.1, pch = 20)

I think that mba.surf from the MBA package would be a good choice for the smoothing, and as larrydag above suggests, persp would be good to image it. The code below is from the help page for the mba.surf function (swap LIDAR for your 3 column dataframe):
data(LIDAR)
mba.int <- mba.surf(LIDAR, 300, 300, extend=TRUE)$xyz.est
# Two ways of imaging....
image(mba.int, xaxs="r", yaxs="r")
persp(mba.int, theta = 135, phi = 30, col = "green3", scale = FALSE,
ltheta = -120, shade = 0.75, expand = 10, border = NA, box = FALSE)

If you are able to create a 2D matrix (x,y) with the value being the z-axis value you could use the following
persp
Here is an example from R Graph Gallery. persp example

require(misc3d)
a <- 2/5
wsqr <- 1 - a^2
w <- sqrt(wsqr)
denom <- function(a,w,u,v) a*((w*cosh(a*u))^2 + (a*sin(w*v))^2)
fx <- function(u,v) -u + (2*wsqr*cosh(a*u)*sinh(a*u)/denom(a,w,u,v))
fy <- function(u,v) 2*w*cosh(a*u)*(-(w*cos(v)*cos(w*v)) - (sin(v)*sin(w*v)))/denom(a,w,u,v)
fz = function(u,v) 2*w*cosh(a*u)*(-(w*sin(v)*cos(w*v)) + (cos(v)*sin(w*v)))/denom(a,w,u,v)
parametric3d(fx = fx, fy = fy, fz = fz,
umin = -17,
umax = 17,
vmin = -77,
vmax = 77,
n = 100,
color = c("grey17","grey21","red4","darkred","red4","grey21","grey17"),
engine = "rgl")

Related

How to create minimum bounding rectangle over complete dataset in R

Say I have a set of coordinates like this, for example:
m <- data.frame(replicate(2,sample(0:9,20,rep=TRUE)))
And I want to draw a box around all of the points so that it creates a minimum bounding rectangle.
a <- bounding.box.xy(m)
plot(m)
par(new=T)
plot(a, main="Minimum bounding rectangle")
But the box doesn't go around all of the points.
I am also interested in drawing a standard deviation circle/ellipse around these points but I don't know the function for this.
RECTANGLE
You can obtain the value of minimum and maximum x and y and then draw polygon using those values. Try this:
set.seed(42)
m <- data.frame(replicate(2,sample(0:9,20,rep=TRUE)))
lx = min(m$X1)
ux = max(m$X1)
ly = min(m$X2)
uy = max(m$X2)
plot(m)
title(main = "Minimum bounding rectangle")
polygon(x = c(lx, ux, ux, lx), y = c(ly, ly, uy, uy), lty = 2)
POLYGON
More discussion about drawing a curve around a set of points can be found here. One way is to exploit the chull command for creating convex hull.
First import the following function
plot_boundary <- function(x,y,offset = 0,lty = 1,lwd = 1,border = "black",col = NA){
# 'offset' defines how much the convex hull should be bumped out (or in if negative value)
# relative to centroid of the points. Typically value of 0.1 works well
BX = x + offset*(x-mean(x))
BY = y + offset*(y-mean(y))
k2 = chull(BX,BY)
polygon(BX[k2],BY[k2],lty = lty,lwd = lwd,border = border,col = col)
}
Then you can generate data and plot boundary around it.
set.seed(242)
m <- data.frame(replicate(2,sample(0:9,20,rep=TRUE)))
plot(m, xlim = c(0,10), ylim = c(0,10))
title(main = "Minimum bounding rectangle")
plot_boundary(x = m$X1, y = m$X2, lty = 2)
ELLIPSE
set.seed(42)
A = data.frame(x = rnorm(20, 25, 4), y = rnorm(20, 11, 3))
B = data.frame(x = rnorm(20, 12, 5), y = rnorm(20, 5, 7))
plot(rbind(A,B), type = "n", ylim = c(-10,20), xlim = c(0,40), asp = 1)
require(ellipse)
red_eli = ellipse(cor(A$x,A$y), scale = c(sd(A$x), sd(A$y)),
centre = c(mean(A$x), mean(A$y)))
blue_eli = ellipse(cor(B$x,B$y), scale = c(sd(B$x), sd(B$y)),
centre = c(mean(B$x), mean(B$y)))
points(A, pch = 19, col = "red")
points(B, pch = 18, col = "blue")
lines(red_eli, col = "red")
lines(blue_eli, col = "blue", lty = 2)

R: plot circular histograms/rose diagrams on map

I am trying to plot rose diagrams/ circular histograms on specific coordinates on a map analogous to drawing pie charts on a map as in the package mapplots.
Below is an example generated with mapplots (see below for code), I'd like to replace the pie charts with rose diagrams
The package circular lets me plot the rose diagrams, but I am unable to integrate it with the mapplots package. Any suggestions for alternative packages or code to achieve this?
In response to the question for the code to make the map. It's all based on the mapplots package. I downloaded a shapefile for the map (I think from http://www.freegisdata.org/)
library(mapplots)
library(shapefiles)
xlim = c(-180, 180)
ylim = c(-90, 90)
#load shapefile
wmap = read.shapefile ("xxx")
# define x,y,z for pies
x <- c(-100, 100)
y <- c(50, -50)
z1 <- c(0.25, 0.25, 0.5)
z2 <- c(0.5, 0.2, 0.3)
z <- rbind(z1,z2)
# define radii of the pies
r <- c(5, 10)
# it's easier to have all data in a single df
plot(NA, xlim = xlim, ylim = ylim, cex = 0.75, xlab = NA, ylab = NA)
draw.shape(wmap, col = "grey", border = "NA")
draw.pie(x,y,z,radius = r, col=c("blue", "yellow", "red"))
legend.pie (x = -160, y = -70, labels = c("0", "1", "2"), radius = 5,
bty = "n", cex = 0.5, label.dist=1.5, col = c("blue", "yellow", "red"))
the legend for the pie size can then be added using legend.bubble
Have a look at this example, you can use the map as background an plot your rose diagrams withPlotrix or ggplot2. In either case you would want to overlay multiple of these diagrams on top of your map which is easy to do in ggplot, just have a look at the example.
I discovered subplot() in the package Hmisc, which seems to do exactly what I wanted. Below is my solution (without the map in the background, which can be plotted using mapplots). I am open to suggestions on how to improve this though...
library(Hmisc)
library (circular)
dat <- data.frame(replicate(2,sample(0:360,10,rep=TRUE)))
lat <- c(50, -40)
lon <- c(-100, 20)
# convert to class circular
cir.dat <- as.circular (dat, type ='angles', units = 'degrees', template = 'geographic', modulo = 'asis', zero = 'pi/2', rotation = 'clock')
# function for subplot, plots relative frequencies, see rose.diag for how to adjust the plot
sub.rose <- function(x){
nu <- sum(!is.na(x))
de <- max(hist(x, breaks = (seq(0, 360, 30)), plot = FALSE)$counts)
prop <- nu/de
rose.diag(x, bins = 12, ticks = FALSE, axes = FALSE,
radii.scale = 'linear',
border = NA,
prop = prop,
col = 'black'
)
}
plot(NA, xlim = xlim, ylim = ylim)
for(i in 1:length(lat)){
subplot(sub.rose(cir.dat[,i]), x = lon[i], y = lat[i], size = c(1, 1))
}

Convert colors to imitate greyscale printing

When reading this question, I started to think whether it would be possible to convert colors to imitate an average greyscale printer (assuming that your screen is calibrated)? Finding an approvable approximation would save paper.
For example, how to convert these colors to see whether the light and dark blues and reds can be differentiated on paper?
temp <- rgb2hsv(239, 138, 98, maxColorValue=255)
Rl <- hsv(h = temp[1,], s = 0.5, v = 1)
Rd <- hsv(h = temp[1,], s = 0.5, v = 0.4)
temp <- rgb2hsv(103, 169, 207, maxColorValue=255)
Cl <- hsv(h = temp[1,], s = temp[2,], v = 1)
Cd <- hsv(h = temp[1,], s = temp[2,], v = 0.4)
plot(1:4, type = "p", col = c(Rl, Rd, Cl, Cd), pch = 19, cex = 8, xlim = c(0,5), ylim = c(0,5))
Use an HCL palette with chroma set to zero to create greyscale values that are indistinguishable to the human eye.
library(colorspace)
n <- 10
cols <- rainbow_hcl(n)
plot(seq_len(n), cex = 5, pch = 20, col = cols)
greys <- rainbow_hcl(n, c = 0)
plot(seq_len(n), cex = 5, pch = 20, col = greys)
If you want to generate the greys from your original colours, use the scales package.
library(scales)
greys2 <- col2hcl(cols, c = 0)
plot(seq_len(n), cex = 5, pch = 20, col = greys2)
The desaturate() function in the `colorspace package can also be used to convert colors to their gray levels only. This collapses chroma (colorfulness) in the HCL (or polar CIELUV) representation of the colors.
plot(1:4, type = "p",
col = colorspace::desaturate(c(Rl, Rd, Cl, Cd)),
pch = 19, cex = 8, xlim = c(0,5), ylim = c(0,5))
The col2grey (and/or col2gray) function in the TeachingDemos package uses one common method for doing this. The idea is to see what your colors will look like when printed or copied in grayscale instead of color.
You can use one of the 3 conversion algorithms outlined here, and just determine if they're outside whatever tolerance you think is too similar.

How to plot bivariate normal contour in R [duplicate]

I have been playing around with the MASS package and can plot the two bivariate normal simply using image and par(new=TRUE) for example:
# lets first simulate a bivariate normal sample
library(MASS)
bivn <- mvrnorm(1000, mu = c(0, 0), Sigma = matrix(c(1, .5, .5, 1), 2))
bivn2 <- mvrnorm(1000, mu = c(0, 0), Sigma = matrix(c(1.5, 1.5, 1.5, 1.5), 2))
# now we do a kernel density estimate
bivn.kde <- kde2d(bivn[,1], bivn[,2], n = 50)
bivn.kde2 <- kde2d(bivn2[,1], bivn[,2], n = 50)
# fancy perspective
persp(bivn.kde, phi = 45, theta = 30, shade = .1, border = NA)
par(new=TRUE)
persp(bivn.kde2, phi = 45, theta = 30, shade = .1, border = NA)
Which doesn't look very good, I guess I have to just play around with the axis and stuff.
But if I try a similar approach with the contour the plots do not overlap. They are simply replaced:
# fancy contour with image
image(bivn.kde); contour(bivn.kde, add = T)
par(new=TRUE)
image(bivn.kde2); contour(bivn.kde, add = T)
Is this the best approach to what I want or am I just making it hard on myself? Any suggestions are welcome. Thank you!
Perhaps you can use rgl library. It allows you to create interactive 3d plots.
require(rgl)
col1 <- rainbow(length(bivn.kde$z))[rank(bivn.kde$z)]
col2 <- heat.colors(length(bivn.kde2$z))[rank(bivn.kde2$z)]
persp3d(x=bivn.kde, col = col1)
with(bivn.kde2, surface3d(x,y,z, color = col2))
If you want to plot difference between two surfaces then you can do something like below.
res <- list(x = bivn.kde$x, y = bivn.kde$y, z = bivn.kde$z - bivn.kde2$z)
col3 <- heat.colors(length(res$z))[rank(res$z)]
persp3d(res, col = col3)

R - Plotting two bivariate normals in 3d and their contours respectively

I have been playing around with the MASS package and can plot the two bivariate normal simply using image and par(new=TRUE) for example:
# lets first simulate a bivariate normal sample
library(MASS)
bivn <- mvrnorm(1000, mu = c(0, 0), Sigma = matrix(c(1, .5, .5, 1), 2))
bivn2 <- mvrnorm(1000, mu = c(0, 0), Sigma = matrix(c(1.5, 1.5, 1.5, 1.5), 2))
# now we do a kernel density estimate
bivn.kde <- kde2d(bivn[,1], bivn[,2], n = 50)
bivn.kde2 <- kde2d(bivn2[,1], bivn[,2], n = 50)
# fancy perspective
persp(bivn.kde, phi = 45, theta = 30, shade = .1, border = NA)
par(new=TRUE)
persp(bivn.kde2, phi = 45, theta = 30, shade = .1, border = NA)
Which doesn't look very good, I guess I have to just play around with the axis and stuff.
But if I try a similar approach with the contour the plots do not overlap. They are simply replaced:
# fancy contour with image
image(bivn.kde); contour(bivn.kde, add = T)
par(new=TRUE)
image(bivn.kde2); contour(bivn.kde, add = T)
Is this the best approach to what I want or am I just making it hard on myself? Any suggestions are welcome. Thank you!
Perhaps you can use rgl library. It allows you to create interactive 3d plots.
require(rgl)
col1 <- rainbow(length(bivn.kde$z))[rank(bivn.kde$z)]
col2 <- heat.colors(length(bivn.kde2$z))[rank(bivn.kde2$z)]
persp3d(x=bivn.kde, col = col1)
with(bivn.kde2, surface3d(x,y,z, color = col2))
If you want to plot difference between two surfaces then you can do something like below.
res <- list(x = bivn.kde$x, y = bivn.kde$y, z = bivn.kde$z - bivn.kde2$z)
col3 <- heat.colors(length(res$z))[rank(res$z)]
persp3d(res, col = col3)

Resources