Plot_ly 在 R 中旋转动画
Plot_ly rotate animation in R
我正在尝试制作围绕轴旋转的 3D 图形的动画,并将其打印为 .gif 或视频格式。找不到资源来协助,请指出正确的方向。任何输入表示赞赏。示例如下图:
library(plotly)
x <- iris$Sepal.Length
y <- iris$Sepal.Width
z <- iris$Petal.Length
test3d <- plot_ly(type = "scatter3d", mode = "markers",
x=x, y=y, z=z)
这是摘自我之前的回答
我们可以在没有 shiny 的情况下使用代码,并通过 htmlwidgets::saveWidget
:
library(plotly)
library(htmlwidgets)
library(utils)
N <- 100
x <- rnorm(N, mean = 50, sd = 2.3)
y <- runif(N, min = 0, max = 100)
z <- runif(N, min = 4, max = 70)
luci.frame <- data.frame(x, y, z)
fig <- plot_ly(
type = "scatter3d",
mode = "markers",
data = luci.frame,
x = ~ x,
y = ~ y,
z = ~ z
) %>%
layout(scene = list(camera = list(
eye = list(
x = 1.25,
y = 1.25,
z = 1.25
),
center = list(x = 0,
y = 0,
z = 0)
))) %>%
onRender("
function(el, x){
var id = el.getAttribute('id');
var gd = document.getElementById(id);
Plotly.update(id).then(attach);
function attach() {
var cnt = 0;
function run() {
rotate('scene', Math.PI / 180);
requestAnimationFrame(run);
}
run();
function rotate(id, angle) {
var eye0 = gd.layout[id].camera.eye
var rtz = xyz2rtz(eye0);
rtz.t += angle;
var eye1 = rtz2xyz(rtz);
Plotly.relayout(gd, id + '.camera.eye', eye1)
}
function xyz2rtz(xyz) {
return {
r: Math.sqrt(xyz.x * xyz.x + xyz.y * xyz.y),
t: Math.atan2(xyz.y, xyz.x),
z: xyz.z
};
}
function rtz2xyz(rtz) {
return {
x: rtz.r * Math.cos(rtz.t),
y: rtz.r * Math.sin(rtz.t),
z: rtz.z
};
}
};
}
")
htmlwidgets::saveWidget(partial_bundle(fig), file = "rotate_scatter3d.HTML", selfcontained = TRUE)
utils::browseURL("rotate_scatter3d.HTML")