我从一个简单的交互模型z = 0.5*x*y
开始。目标是使用add_markers()
库使用add_surface()
以及使用plotly
的模型绘制模拟观察结果。
到目前为止,我已经设法模拟数据并绘制它:
library(plotly)
library(magrittr)
x <- rnorm(10000)
y <- rnorm(10000)
z <- 0.5 * x * y
plot_ly() %>% add_markers(x = x, y = y, z = z, marker = list(size = 1))
然后我尝试对模型进行表面绘图:
plot_ly() %>%
add_markers(x = x, y = y, z = z, marker = list(size = 1)) %>%
add_surface(z = matrix(z, 100, 100))
但它会产生与预期完全不同的东西。这大约是从表面图中得到的结果:
我做错了什么?
答案 0 :(得分:1)
一个简单的解决方法是使用:
plot_ly(x = x, y = y, z= z, type = 'mesh3d')
或使用表面图:
library(tidyverse)
grid <- expand.grid(x = seq(from = -3, to = 3, length.out = 100),
y = seq(from = -3, to = 3, length.out = 100))
grid %>%
mutate(z = 0.5 * x * y) %>%
spread(key = y, value = z) %>%
as.matrix() -> z
plot_ly() %>%
add_surface(z = z, x = unique(grid$x), y = unique(grid$y)) %>%
layout(scene = list(xaxis = list(range = c(-2.5, 2.5)),
yaxis = list(range = c(-2.5, 2.5)))) #odd artifact if all values are plotted - check without layout call
或:
model = lm(z ~ x * y)
grid <- expand.grid(x = seq(from = -3, to = 3, length.out = 100),
y = seq(from = -3, to = 3, length.out = 100))
grid$z = predict(model, grid)
并按上述步骤进行
grid %>%
spread(key = y, value = z) %>%
as.matrix() -> z