【问题标题】:Plot trend lines (not planes or smooth surfaces) on interactive, 3-dimensional graphs in R在 R 中的交互式 3 维图形上绘制趋势线(不是平面或光滑表面)
【发布时间】:2020-05-06 23:42:05
【问题描述】:

我想在 R 中的交互式 3 维图形上绘制趋势线(不是平面或光滑表面)。

这是我目前的代码:

library (car)
set.seed(1)
x <- 1:100 + rnorm(100, 5, 5)
y <- x + rnorm(100, 10, 20)
z <- y + rnorm(100, 1, 10)
scatter3d(x = x, y = y, z = z, surface = F)

本质上,我想在该图上绘制一条趋势线,该趋势线穿过该点云中最大可变性的区域。当然,这条趋势线是第一主成分轴。我知道如何对这些数据进行主成分分析:

df <- data.frame(x, y, z)
prcomp(df, center = T, scale. = T)

如何在此散点图上绘制主成分轴?

(我当然愿意使用不同的软件包来创建交互式 3 维散点图。我开始使用 car 软件包中的 scatter3d 函数,因为 plotly 软件包给我带来了麻烦 - 我一直当我尝试使用 plotly 函数创建 3 维绘图​​时收到 WebGL is not supported by your browser - visit https://get.webgl.org for more info 消息。)

谢谢!

【问题讨论】:

    标签: r


    【解决方案1】:

    好的,希望我能正确理解。要绘制主成分,您需要特征向量,这在$rotation 中给出。首先我们建立 3D 图并计算主成分:

    library(rgl)
    set.seed(1)
    x <- 1:100 + rnorm(100, 5, 5)
    y <- x + rnorm(100, 10, 20)
    z <- y + rnorm(100, 1, 10)
    M = cbind(x,y,z)
    pca = prcomp(df, center = T, scale. = T)
    

    我们绘制点:

    plot3d(M)
    

    由于您缩放了主成分,我们需要找到 x、y、z 的均值(或中心)并从那里绘制 PC。而且由于 PC 是一个特征向量,我只是简单地绘制了一个从中心到 100*eigenvector 左右的线段:

    centers = colMeans(M)
    PC1 = rbind(centers,centers+100*pca$rotation[,1])
    colnames(PC1) = c("x","y","z")
    segments3d(PC1,col="blue",lwd=2)
    
    PC2 = rbind(centers,centers+100*pca$rotation[,2])
    colnames(PC2) = c("x","y","z")
    segments3d(PC2,col="orange",lwd=2)
    

    【讨论】:

      【解决方案2】:

      跟进 StupidWolf 的出色回答,这里有一种方法可以让线条在数据的最大值和最小值处停止,而不是任意选择 100 等乘数:

      PC1 <- rbind(pca$center + min(pca$x[, 1]) * pca$rotation[, 1], pca$center + max(pca$x[, 1]) * pca$rotation[, 1])
      colnames(PC1) = c("x", "y", "z")
      segments3d(PC1, col = 1 , lwd = 2)
      
      PC2 <- rbind(pca$center + min(pca$x[, 2]) * pca$rotation[, 2], pca$center + max(pca$x[, 2]) * pca$rotation[, 2])
      colnames(PC2) = c("x", "y", "z")
      segments3d(PC2, col = 2 , lwd = 2)
      
      PC1 <- rbind(pca$center + min(pca$x[, 3]) * pca$rotation[, 3], pca$center + max(pca$x[, 3]) * pca$rotation[, 3])
      colnames(PC1) = c("x", "y", "z")
      segments3d(PC1, col = 3 , lwd = 2)
      

      【讨论】:

        猜你喜欢
        • 2021-05-08
        • 1970-01-01
        • 2022-07-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-02-26
        • 1970-01-01
        相关资源
        最近更新 更多