如何在R的plot_ly 3D图中添加点到NMDS平面的垂直线
在Plotly 3D散点图中添加垂直于NMDS1/NMDS2平面的定位连线
要实现类似scatterplot3d的垂直线定位效果,我们需要为每个数据点添加一条从点本身到NMDS1/NMDS2平面(即x-y平面,z=0)的垂直连线,方便静态查看时定位点的位置。
实现步骤
1. 构造连线数据
为每个原始数据点生成对应的投影点(x、y坐标与原数据一致,z坐标设为0),将原始点和投影点配对,用于绘制单条垂直线段。
2. 绘制散点图并添加连线
在原有散点图基础上,添加线段图层,设置合适的线条样式避免遮挡散点。
完整代码
library(plotly) # 示例数据 cent1 <- structure(list(MHW = structure(c(1L, 2L, 3L, 1L, 2L, 3L), .Label = c("before", "during", "after"), class = "factor"), region4 = structure(c(2L, 2L, 2L, 2L, 2L, 2L), .Label = c("north", "central", "north islands", "south"), class = "factor"), mpa_designation = structure(c(1L, 1L, 1L, 2L, 2L, 2L), .Label = c("smr", "ref"), class = "factor"), NMDS1 = c(-0.00203871468205806, -0.0163789795067529, 0.0992415884324829, -0.0619337823248111, -0.0521942653829068, 0.0558561061282499), NMDS2 = c(-0.073966852764061, 0.0444855390277828, 0.0971028598153799, -0.0813406436228275, 0.0415761480613053, 0.105811130463746), NMDS3 = c(0.0351953529328383, 0.0317522849669617, 0.00538961231383452, -0.0170206229860022, -0.00442410992911777, -0.0548475894376382), centroid_type = c("smr before", "smr during", "smr after", "ref before", "ref during", "ref after"), shapes = c("circle", "circle", "circle", "triangle", "triangle", "triangle")), row.names = c("smr before", "smr during", "smr after", "ref before", "ref during", "ref after"), class = "data.frame") # 生成连线数据:每个点对应原始点和z=0的投影点 line_data <- do.call(rbind, lapply(1:nrow(cent1), function(i) { data.frame( NMDS1 = rep(cent1$NMDS1[i], 2), NMDS2 = rep(cent1$NMDS2[i], 2), NMDS3 = c(cent1$NMDS3[i], 0), group = i # 标记每条线段的分组 ) })) # 绘制基础散点图 fig <- plot_ly(cent1, x = ~NMDS1, y = ~NMDS2, z = ~NMDS3, color = ~MHW, colors = c('#44b89d','#f56969','#4c78b5'), symbol = ~mpa_designation, symbols = c(16, 15), type = "scatter3d", mode = "markers") # 添加垂直定位连线 fig <- fig %>% add_trace( data = line_data, x = ~NMDS1, y = ~NMDS2, z = ~NMDS3, type = "scatter3d", mode = "lines", color = I("gray"), # 用灰色避免干扰散点颜色 line = list(width = 1, dash = "dot"), # 设置线条宽度和虚线样式 showlegend = FALSE # 隐藏连线图例 ) # 调整坐标轴标签(可选) fig <- fig %>% layout( scene = list( xaxis = list(title = "NMDS1"), yaxis = list(title = "NMDS2"), zaxis = list(title = "NMDS3") ) ) fig
自定义说明
- 如果需要将连线画到z轴最小值而非z=0,只需把代码中
NMDS3 = c(cent1$NMDS3[i], 0)的0替换为min(cent1$NMDS3)即可。 - 可根据需求调整连线的颜色、宽度和样式,匹配图表整体风格。
内容的提问来源于stack exchange,提问作者Joshua Smith
相关产品推荐
相关产品推荐

