简体   繁体   English

R:绘制3D交互模型和使用Plotly进行的观察

[英]R: plot 3d interaction model and observations using plotly

I start from a simple interaction model z = 0.5*x*y . 我从一个简单的交互模型z = 0.5*x*y The goal is to plot simulated observations with add_markers() as well as the model with add_surface() using the plotly library. 我们的目标是绘制与模拟观测add_markers()以及与模型add_surface()使用plotly库。

So far I have manage to simulate the data and plot it: 到目前为止,我已经设法模拟数据并将其绘制:

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))

This is what the plot looks like: 这是情节的样子: 在此处输入图片说明

I then tried to surface plot the model: 然后,我尝试对模型进行表面绘制:

plot_ly() %>% 
   add_markers(x = x, y = y, z = z, marker = list(size = 1)) %>%
   add_surface(z = matrix(z, 100, 100))

But it produces something completely different to what it would be expected. 但是它产生的东西与预期的完全不同。 This is approximately the result that would be expect from the surface plot: 这大约是表面图所预期的结果: 在此处输入图片说明

What am I doing wrong? 我究竟做错了什么?

An easy workaround is to use: 一个简单的解决方法是使用:

plot_ly(x = x, y = y, z= z, type = 'mesh3d') 

在此处输入图片说明

Or using surface plot: 或使用曲面图:

  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

or: 要么:

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)

and proceed as above 并按上述步骤进行

 grid %>%       
    spread(key = y, value = z) %>%
    as.matrix() -> z

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM