I am trying to print a 3d plot from within a loop in RMarkdown to an HTML.
It is a bit like this question: How to include multiple plot3d in markdown (knitr) under a loop
However, the answers there involve saving the plots from each iteration and then plotting at the end. I am wondering if there is a way to have it "dynamically" print with each iteration.
For example, for 2d base plots or ggplots, you can use print()
to dyanmically print within each loop iteration, I wonder if there is anything like that.
Ideally, the code block would allow "result = 'asis'", for dynamic printing of sub-headings.
For example, this is the sort of behaviour I am hoping for:
x <- sort(rnorm(1000))
y <- rnorm(1000)
z <- rnorm(1000) + atan2(x,y)
cols <- c("red", "orange", "green", "blue", "purple")
for(i in 1:3){
plotlab <- "
# 3D Plot for Sample %s
Here we plot a 3d PCA plot for this sample.
"
cat(sprintf(plotlab, i)) #this prints out a dynamic title if result='asis' is in the code options
plot3d(x, y, z, col = cols[i])
print( rglwidget() ) ## this is what I hope to achieve
}
Thank you so much for any help!
rgl
is more likeleaflet
or other HTML widgets than like base plots. Here's an example that plots your 3 plots, with labels between:Notice that you don't use
cat()
to print the labels, you have to generate HTML for them, because all the plotting happens when theallplots
object is printed.