Weird behaviour than animating lines with rgl and rglwidget - r

I am trying to follow help and Internet examples to create a very simple animation of a 3d-line in R. This is just a test and my final goal is to use this functionality to visually verify results of some geometrical transformations on 3d-movement data that I am analysing. So basically I need nothing more than a ‘3d-player’ interface that allows for usual interaction (rotation, zoom, play, stop, slide).
I figured out that rgl package does the job and I am able to use it for the sphere/points animation. But now I need to use it on lines and I get very strange results. In the example below there are 4 points and two lines (cyan and red) that connect the same points but the red line is for some reason in the ‘wrong’ place. The animation doesn’t make sense neither. Now, I am thinking may be it is impossible to do >> to animate more than one vertex with more than one attribute? But I don’t see this in documentation and obviously it is possible because line is animated! I spent quite a long time trying to figure out what is going on and will appreciate any help/advise/directions. many thanks
Ps: Tthe code below is a chunk in the markdown file and I am using Rstudio.
require(rgl)
require(rglwidget)
p11=c(0,0,0)
p21=c(50,50,0)
p12=c(50,0,0)
p22=c(10,50,50)
saveopts <- options(rgl.useNULL = TRUE)
did=list()
did[[1]]=plot3d(rbind(p11,p21,p12,p22), type="s", alpha = 1, lwd = 5, col = c('brown','darkgreen','orange','green'))
did[[2]]=spheres3d(c(100,100,100), alpha = 1, lwd = 5, col = "blue",radius=2)
did[[3]]=lines3d(rbind(p11,p21),lwd=8, col='cyan',alpha=.9)
did[[4]]=planes3d(0, 0, 1, 0, alpha=.4, col='green')
did[[5]]=lines3d(rbind(p11,p21),lwd=2, col='red')
aspect3d(1, 1, 1)
did[[6]]=grid3d(c("x-", "z-"),at = NULL,col = "gray",lwd = .5,lty = 1,n = 5)
sceneT = rglwidget(elementId = "plot3dT",width=500, height=300) #%>%
rgl.ids()
rgl.attrib(id=did[[3]],attrib = c(1:length(did[[3]])))
playwidget(sceneT,list(
vertexControl(values = rbind(c(0,0,0,0,0,0),c(50,50,50,50,50,50)),
vertices = 1:6, attributes = "z", objid = did[[4]], param = 1:2,interp =T),
vertexControl(values = r1,
vertices = 1:2, attributes = c('x',"y","z",'x',"y","z"), objid = did[[5]], param = 1:2,interp =T)),
start = 1, stop = 2, step = .1, precision = 3)
options(saveopts)

Related

How to define printing whole graph in ggplot2?

I am using a package called microbiomeMarker to plot a cladogram (ggtree). It was taking too long to print so I implemented the Cairo package so that the printing is faster (there's a considerable change thankfully.
cladogram<-plot_cladogram(
OTU_lefse_res,
color = c("#7570B3","#D95F02"),
only_marker = TRUE,
branch_size = 0.2, #beyond this point everything is default values
alpha = 0.2,
node_size_scale = 1,
node_size_offset = 1,
clade_label_level = 4,
clade_label_font_size = 4,
annotation_shape = 22,
annotation_shape_size = 5,
group_legend_param = list(),
marker_legend_param = list()
)
ggsave(
filename = "16S_Marker_Cladogram.png",
units = "px",
dpi = 300,
type = "cairo-png"
)
My issue is that when it gets saved, the graph is zoomed in (as far as I can figure to the bottom right corner of the legend) so I can't see the cladogram. I've also tried saving it as a pdf, changing the dpi to 900, defining the size by pixels, setting in the ggplot "coord_fixed()"... I'm at a loss, I googled the issue but I can't find anyone having a similar issue. The example data of the package works fine. I've got about 10x the amount of data to be plotted, so I expect some delay, but I don't understand why I can't get it right.
If I don't set a printing device and just do:
plot_cladogram(
OTU_lefse_res,
color = c("#7570B3","#D95F02"),
only_marker = TRUE,
branch_size = 0.2,
alpha = 0.2,
node_size_scale = 1,
node_size_offset = 1,
clade_label_level = 4,
clade_label_font_size = 4,
annotation_shape = 22,
annotation_shape_size = 5,
group_legend_param = list(),
marker_legend_param = list()
)
I don't get any output in the plot window. Any ideas of something else I can try?

esem.diagram() in R - remove rectangles from items in diagram

I am performing ESEM with psych.
esem.diagram returns a graph in which the items overlap.
I would like to ask for some help with fixing the overlap or removing the rectangles please :)
My Code:
esem1 <- esem(modelESEM, varsX=c(1:33),varsY=c(34:41) ,nfX = 4, nfY = 1, fm = "minres",
rotate = "promax", plot = TRUE, cor = "cor", use = "pairwise")
esem.diagram(esem=esem1, cut=0.4)

Animated 3D scatterplot and save it as gif in R

I want to plot a animated 3D scatterplot and save it as gif. I followed the code provided by the R Graph Gallery example: https://www.r-graph-gallery.com/3-r-animated-cube.html.
library(rgl)
library(magick)
options(rgl.printRglwidget = TRUE)
# Let's use the iris dataset
# iris
# This is ugly
colors <- c("royalblue1", "darkcyan", "oldlace")
iris$color <- colors[ as.numeric( as.factor(iris$Species) ) ]
# Static chart
plot3d( iris[,1], iris[,2], iris[,3], col = iris$color, type = "s", radius = .2 )
# We can indicate the axis and the rotation velocity
play3d( spin3d( axis = c(0, 0, 1), rpm = 20,dev = cur3d()),startTime = 0, duration = 10 )
# Save like gif
movie3d(
movie="3dAnimatedScatterplot",
spin3d( axis = c(0, 0, 1), rpm = 20,dev = cur3d()),
startTime = 0,
duration = 10,
dir = ".",
type = "gif",
clean = T,
fps=10,
convert=T
)
plot3d was successed output a 3d scatter plot.
Static 3d scatter plot
But the final output: 3dAnimatedScatterplot.gif,just a black image
3dAnimatedScatterplot.gif
when I set clean=F, all frame images are black. So, I guess the play3d() was not working.
Can anyone provide any help to me ? Thanks a lot !
Most likely snapshot3d isn't working for you. Try it with the option webshot = FALSE instead of the default webshot = TRUE. That uses a different mechanism for saving the image.

R: Get quantmod's chartSeries and AddTA to not show last value

When using chartSeries, by default it also shows on the top left of the plot the last value. Is there any way to prevent it from doing it?
When adding a new TA with addTA, you can avoid the last value on the plot by setting the argument legend = "", but only if you're making a new plot for the TA. If the TA is on a previously plotted graphic, it'll show the last value regardless of what you put in the legend argument.
getSymbols ("AAPL", src = "google")
chartSeries(AAPL)
What can I use here to prevent it from printing the last value on the plot?
addTA(EMA(Cl(AAPL)), on = 1, legend = "")
This still prints the last value on the top left of the plot. The weird part is that it doesn't do it if you're plotting on a new plot like this:
addTA(EMA(Cl(AAPL)), legend = "")
Is it like this by default, or is there something I can do to get around it?
The last value is shown by default (yes, annoyingly). You'll likely have to modify the source code to remove the last number showing in addTA.
I don't use addTA, but rather add_TA and chart_Series, because I think they look much better (second generation charts for quantmod). Here is a solution that removes the last number from showing for the add_TA version. But you must be willing to modify the source code.
In add_TA, you'll need to modify approximately lines 56-60 of the source:
Replace the text.exp, which is this:
# this is inside add_TA:
if (is.na(on)) {
plot_object$add_frame(ylim = c(0, 1), asp = 0.15)
plot_object$next_frame()
text.exp <- expression(text(x = c(1, 1 + strwidth(name)),
y = 0.3, labels = c(name, round(last(xdata[xsubset]),
5)), col = c(1, col), adj = c(0, 0), cex = 0.9,
offset = 0, pos = 4))
plot_object$add(text.exp, env = c(lenv, plot_object$Env),
with these modifications:
if (is.na(on)) {
plot_object$add_frame(ylim = c(0, 1), asp = 0.15)
plot_object$next_frame()
text.exp <- expression(text(x = c(strwidth(name)), # <- affects label on the subchart
y = 0.3, labels = name, col = c(col), adj = c(0), cex = 0.9,
offset = 1, pos = 4))
plot_object$add(text.exp, env = c(lenv, plot_object$Env),
expr = TRUE)
...
and assign this modified code to a new variable, called say add_TA.mine:
add_TA.mine <- function (x, order = NULL, on = NA, legend = "auto", yaxis = list(NULL,
NULL), col = 1, taType = NULL, ...)
{
lenv <- new.env()
lenv$name <- deparse(substitute(x))
lenv$plot_ta <- function(x, ta, on, taType, col = col, ...) {
xdata <- x$Env$xdata
....
[all the code for the rest of the function with modifications]....
}
}
plot_object
}
Now, just run the code with the modified function
library(quantmod)
getSymbols("AAPL")
environment(add_TA.mine) <- environment(get("add_TA", envir = asNamespace("quantmod")))
assignInNamespace(x = "add_TA", value = add_TA.mine, ns = "quantmod")
chart_Series(AAPL, subset = "2017")
add_TA(RSI(Cl(AAPL)))
quantmod:::add_TA(RSI(Cl(AAPL)))
You can see the last value is no longer printed:
(You could make the same kinds of changes in the old addTA code (perhaps via chartSeries if you really want to stick to the old plots)
If you're happy with the changes, and want to make them permament in add_TA, you can recompile the quantmod source code yourself with your modifications (i.e. you need to download the quantmod source code and recompile the package) . If you make a mess of things you can always redownload the original quandmod source code again.

How to change the color and width of lines with par function in R

I have a question about the par function in R.
I want to change the color and/or width of a line in a graph with par function. (I am using par function because the gaps.plot command below does not allow "col" option to be included. The gaps.plot command is used after the synth command).
So, I used the following command. But I noticed that the lines of the BOX are changed rather than the lines of the GRAPHS.
synth1<-read.csv(file="C:\\Users\\Research\\R\\synthinR_v4.csv",header=TRUE)
attach(synth1)
library("Synth")
dataprep.out34 <- dataprep(foo = synth1, predictors = c("lncdsales", "md1", "md2","md3", "md4", "md5", "md6", "md7", "md8", "md9", "md10", "md11", "yd1", "yd2", "yd3", "yd4", "yd5", "yd6", "yd7", "yd8"), predictors.op = "mean", time.predictors.prior = -13:1, dependent = "lndigital", unit.variable = "artistalbumcode", time.variable = "release", treatment.identifier = 34, controls.identifier = c(1:33, 35:49), time.optimize.ssr = -13:1, time.plot = -13:25)
synth.out34 <- synth(data.prep.obj = dataprep.out34, method = "BFGS")
par(lwd = 2, col="#cccccc")
gaps.plot(synth.res = synth.out34, dataprep.res = dataprep.out34, Ylab = " Log Digital Sales ", Xlab = "Release", Ylim = c(-7, 7) , Main = NA)
Does anyone know how to fix this problem??
Thank you in advance for your willingness to help. I greatly appreciate it!
The col argument to par sets the default plotting colour (i.e. when col is not explicitly specified in plotting calls), but unfortunately col = "black" is hard-coded into the source of gaps.plot.
You can make a modified copy of the function by either (1) viewing the source (F2 in RStudio, or just executing gaps.plot), editing it and assigning it to a new object, or (2) doing something like the following:
gaps.plot2 <- eval(parse(text=gsub('col = "black"', 'col = "red"',
deparse(Synth:::gaps.plot))))
and then using gaps.plot2 as you would use gaps.plot:
gaps.plot2(synth.res = synth.out34, dataprep.res = dataprep.out34,
Ylab = " Log Digital Sales ", Xlab = "Release", Ylim = c(-7, 7) ,
Main = NA)
Alter the lwd similarly. For example to make lines red and have width of 3, use nested gsub calls like this:
gaps.plot2 <- eval(parse(text=gsub('lwd = 2', 'lwd = 3',
gsub('col = "black"', 'col = "red"',
deparse(Synth:::gaps.plot)))))

Resources