Rotate persp3d plot and save images as png - r

With R, I am using the persp3d function of the rgl package to get a nice 3d plot.
Now I want to rotate the persp3d function and save each small rotated image as a png file. I want then to include the png in my latex presentation with the command animategraphic.
I therefore want to aks, how I can do this?
I need them in a way that I can implement them in latex, so the names of the png files should somehow be like a1,a2 and so on...
My code to create the persp3d plot is:
persp3d(x, y, z, theta=50, phi=25, expand=0.75, col=color[zcol2],
ticktype="detailed", xlab="", ylab="", zlab="",axes=FALSE)
I then tried to spin it with the spin3d command:
spind3d(rpm=3)
which does not work. Also this would not save pngs to my drive?

Here is an alternative using the functions spin3d to change the view, and movie3d to save the images.
library(rgl)
x <- seq(-10, 10, length= 30)
y <- x
f <- function(x,y) { r <- sqrt(x^2+y^2); 10 * sin(r)/r }
z <- outer(x, y, f)
z[is.na(z)] <- 1
persp3d(x,y,z,theta=0,phi=25, col = "lightblue",
ticktype="detailed", xlab="", ylab="", zlab="",axes=FALSE)
movie3d(spin3d(axis = c(0,0,1), rpm = 10), duration=6, type = "png")
Note that by default movie3d saves the files in the folder set by tempdir().

x=1:10
y=1:10
z=matrix(runif(100),10,10)
persp3d(x,y,z,theta=50,phi=25)
then loop over theta or phi, use view3d to set the angle, snapshot3d to make a PNG
theta = seq(0,360,len=10)
for(i in 1:10){
snapshot3d(file=paste0("spin-",i,".png"))
view3d(theta=theta[i])
}
You might want to loop over phi instead of theta. Anyway, that gets you the PNGs you want, doesn't it?

May be someone need. I used the following combination for persp3Drgl:
userMat = matrix(data = c( 0.4892255, 0.8709987, 0.04464279, 0,
-0.5228708, 0.2519508, 0.81430787, 0,
0.6980215, -0.4217298, 0.57868713, 0,
0.0000000, 0.0000000, 0.0000000, 1
), nrow = 4, ncol = 4)
persp3Drgl(..., userMatrix = userMat )
par3d( windowRect=c( 0,0,100,100 ) )
snapshot3d( file.path(plotDir, "3D.png"), top = TRUE )
Besides, I used to track userMatrix value (after rotation the plot by mouse) the following command
userMat = par3d(no.readonly=TRUE)$userMatrix

Related

Function plotting in r

x<-seq(-2*pi,2*pi) #range of x
f<-(2*(abs(sin(x)))+(1/2))
f1<-function(x)(2*(abs(sin(x)))+(1/2))
x1=seq(-2*pi,-pi)
g<-2*cos(x1)
gun<- function(y) 2*cos(x1)
curve(gun, from=-2*pi, to=-pi, type='l')
So, I want to plot these functions in the same graph but I get an error when I try to plot g:
Error in curve(gun, from = -2 * pi, to = -pi, type = "l") :
'expr' did not evaluate to an object of length 'n'
I am not sure how to fix this, I've seen people use Vectorize() but it doesn't seem to help.
Any advices?
You are calling data stored in your environment in your function. It should be referencing the data that is passed into it.
x<-seq(-2*pi,2*pi) #range of x
f<-(2*(abs(sin(x)))+(1/2))
f1<-function(x)(2*(abs(sin(x)))+(1/2))
g<-2*cos(x1)
gun<- function(y) 2*cos(y)
curve(gun, from=-2*pi, to=2*pi, type='l')
to add the second function to the plot you can run this
curve(f1, from = -2*pi, to = 2*pi, type = 'l', col = "red", add = TRUE)

Adding symbols and information to Phylogenetic tree

I am drawing a phylogenetic tree, and I would like to add something like a 'dead symbol̈́̈́' (e.g a skull) in the tips of the extinct species.
I would also like to add an x-axes bar with latex symbols in the branching times (e.g $\Delta t_i$ or numbers) marked with dots.
What I have so far is this tree. I would like to add the dead symbol right after the green dotted line in this case.
library(ape)
rec1 = '((B:1,A:1):1,(F:1,C:1.5):0.5);'
rec1 = read.tree(text = rec1)
plot(rec1,show.tip.label = F,edge.color = c("black","black","black","black","darkgreen","black"),edge.width = 2,edge.lty = c(rep(1,4),4,1))
One possibility is using ggtree. As in:
https://guangchuangyu.github.io/2018/03/annotating-phylogenetic-tree-with-images-using-ggtree-and-ggimage/
#source("https://bioconductor.org/biocLite.R")
#biocLite("BiocUpgrade") # you may need this
#biocLite("ggtree")
library(ggtree)
tree<-rtree(10)
pg<-ggtree(tree)
d <- data.frame(node = as.character(10:15),
images = c("https://i.imgur.com/8VA9cYw.png",
"https://i.imgur.com/XYM1T2x.png",
"https://i.imgur.com/EQs5ZZe.png",
"https://i.imgur.com/2xin0UK.png",
"https://i.imgur.com/hbftayl.png",
"https://i.imgur.com/3wDHW8n.png"))
pg %<+% d + geom_nodelab(aes(image=images), geom="image")
With phylopic
#install.packages('rphylopic')
library(rphylopic)
string<-name_search(text = "Homo sapiens")
selectstr<-string[2,]
string2<-name_images(uuid = selectstr)$same[[1]]$uid
tree<-rtree(10)
phylopic_info <- data.frame(node = c(12,13),
phylopic = string2)
nt<-ggtree(tree)
nt %<+% phylopic_info +
geom_nodelab(aes(image=phylopic), geom="phylopic", alpha=.5, color='steelblue')
I can see two options how to display an "extinct" symbol on a tree tip.
Use a Unicode symbol with an appropriate font that can display it as per this blog.
Add a raster image onto the tree plot.
The following code will display an extinction symbol next to the green edge in your tree. It draws on information found here.
library(jpeg)
logo <- readJPEG("Downloads/Symbol1.jpg")
logo2 <- as.raster(logo)
r <- nrow(logo2)/ncol(logo2) # aspect ratio
s <- 0.4 # symbol size
# display plot to obtain its size
plot(rec1, edge.color = c("black","black","black","black","darkgreen","black"),
edge.width = 2, edge.lty = c(rep(1,4),4,1))
lims <- par("usr") # plot area size
file_r <- (lims[2]-lims[1]) / (lims[4]-lims[3]) # aspect ratio for the file
file_s <- 480 # file size
# save tree with added symbol
png("tree_logo.png", height=file_s, width=file_s*file_r)
plot(rec1, show.tip.label = F,
edge.color = c("black","black","black","black","darkgreen","black"),
edge.width = 2, edge.lty = c(rep(1,4),4,1))
rasterImage(logo2, 1.6, 2.8, 1.6+s/r, 2.8+s)
# add axis
axisPhylo()
mtext(expression(Delta*italic("t")["i"]), side = 1, line = 3)
dev.off()

biwavelet package: "axis" is not working

I am using biwavelet package to conduct wavelet coherence analysis. When I want to set my own x ticklabel, I find axisis not working. The following gives a reproducible example. Thanks.
require(biwavelet)
t1 <- cbind(1:100, rnorm(100))
t2 <- cbind(1:100, rnorm(100))
wtc.t1t2 <- wtc(t1,t2,nrands = 10)
plot(wtc.t1t2, plot.cb = TRUE, plot.phase = TRUE,xaxt='n')
axis(1,at = seq(10,100,10),labels = seq(1,10,1))
The thing that was breaking your plot was plot.cb = TRUE.
In the source code for plot.biwavelet the author notes the following about the plot.cb option:
## Add color bar: this must happen after everything, otherwise chaos
ensues!
So that was the problem -- you invoked axis() after plot.cb and chaos ensued. However, you can manually add back the color bar using image.plot from the fields package, after having run plot without plot.cb then having added your axis().
pacman::p_load(biwavelet,fields)
t1 <- cbind(1:100, rnorm(100))
t2 <- cbind(1:100, rnorm(100))
wtc.t1t2 <- wtc(t1,t2,nrands = 10)
plot(wtc.t1t2, plot.phase = TRUE,xaxt='n')
axis(1,at = seq(10,100,10),labels = seq(1,20,2))
image.plot( zlim=c(0,25), legend.only=TRUE)
You can customize the ticks and the color bar to your liking this way!

Adding axis titles in gplot using filled.contour in R

This is my reproducible code example. Everything looks as it should in the graph, except the axis titles/labels are not being added. I am really struggling to figure out how to fix it, despite following the directions in the function documentation. Help will be much appreciated - thanks in advance.
output <- matrix(data = c(0.7,0.5,0.3,0.8,0.6,0.4,0.9,0.7,0.5,1,0.8,0.6),nrow=3,
ncol=4)
# Change column names
colnames(output) <- c(10,20,30,40)
# Change row names
rownames(output) <- c(1,2,3)
library(gplots)
matrix.axes <- function(data) {
# Do the rows, las=2 for text perpendicular to the axis
x <- (1:dim(data)[1] - 1) / (dim(data)[1] - 1);
axis(side=1, at=x, labels=rownames(data), las=1);
# Do the columns
x <- (1:dim(data)[2] - 1) / (dim(data)[2] - 1);
axis(side=2, at=x, labels=colnames(data), las=2);
}
# Not necessary to save as pdf unless this is part of the problem
# save to pdf
# pdf("C:/Test.pdf")
# Plot results
filled.contour(output,plot.title=title(main="Method"),
xlab='Case number',ylab='Sample number',
plot.axes=matrix.axes(output))
# dev.off()
Your xlab = and ylab = need to be inside the plot.title() function:
filled.contour(output,
plot.title = title(main = "Method", xlab='Case number', ylab='Sample number'),
plot.axes = matrix.axes(output))

Incorrectly recognized math symbol from PDF in LaTeX

I am generating plot in R and save it as PDF with:
pdf(
file='Plots/errors.pdf',
height=4,
width=7,
onefile=TRUE,
family='Helvetica',
pointsize=12
)
# Here is my graphics
dev.off()
Somewhere inside graphics I have:
mtext(
expression(mu[H1])
)
It produces neat PDF with correctly processed greek letter µ.
Then I import this PDF in LaTeX article with:
\includegraphics[width=1\textwidth,height=0.4\textheight]{../Plots/errors.pdf}
But instead of µ sign of infinity (∞) is displayed.
Why?
For seamless integration without the encoding issues, I would look at package 'TikzDevice'. It outputs Tikz images in LaTeX format. For example:
require(tikzDevice)
setwd("/Path/To/LaTeX/Files/")
#Names of LaTeX symbols
syms <- c('alpha', 'theta', 'tau', 'beta', 'vartheta', 'pi', 'upsilon', 'gamma', 'varpi', 'phi', 'delta', 'kappa', 'rho', 'varphi', 'epsilon', 'lambda', 'varrho', 'chi', 'varepsilon', 'mu', 'sigma', 'psi', 'zeta', 'nu', 'varsigma', 'omega', 'eta', 'xi', 'Gamma', 'Lambda', 'Sigma', 'Psi', 'Delta', 'Xi', 'Upsilon', 'Omega', 'Theta', 'Pi', 'Phi')
len <- length(syms)
# random colors (red, green, blue)
r <- round(runif(len), 2)
g <- round(runif(len), 2)
b <- round(runif(len), 2)
# calculate dummy data points
x <- runif(50,1,10)
y <- x + rnorm(length(x))
fit <- lm(y ~ x)
rsq <- summary(fit)$r.squared
rsq <- signif(rsq,4)
# plot the result, will create symbol-regression.tex in the working
# directory the first time this is run it may take a long time because the
# process of calulating string widths for proper placement is
# computationally intensive, the results will get cached for the current R
# session or will get permenantly cached if you set
# options( tikzMetricsDictionary='/path/to/dictionary' ) which will be
# created if it does not exist. Also if the flag standAlone is not set to
# TRUE then a file is created which can be included with \include{}
tikz('symbolr.tex', width = 4,height = 4,pointsize = 12)
# The syntax is mar=c(bottom, left, top, right).
par(mar=c(2,2,2,2))
# plot the box and the regression line
plot(x, y, type='n', xlab='', ylab='')
box()
abline(fit)
# add the latex symbols as points
text(x, y, paste('\\color[rgb]{',r,',',g,',',b,'}{$\\',syms,'$}',sep=''))
# Display the correlation coefficient
mtext(paste("Linear model: $R^{2}=",rsq,"$" ),line=0.5)
# and the equation of the line
legend('bottom', legend = paste("$y = ", round(coef(fit)[2],3),'x +', round(coef(fit)[1],3), '$', sep=''), bty= 'n')
# Close the device
dev.off()
Then all you have to do is include the file just output from R in your LaTeX document.

Resources