You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在RStudio中用plot3D绘制3D散点图及配色问题求助

基于plot3D包按"N"值设置散点配色方案的解决方法

一、静态3D散点图(带垂直线版本)

在scatter3D()函数中,通过col参数结合颜色映射逻辑,就能实现按"N"值的配色:

  • 先将"N"值归一化到0-1区间,用于匹配颜色梯度
  • 选择合适的调色板(基础R调色板或第三方包调色板均可)
  • 将归一化后的值映射到调色板上

示例代码:

library(plot3D)

# 假设数据框为df,包含x、y、z、N列
# 手动归一化N值(无需额外包)
df$N_norm <- (df$N - min(df$N)) / (max(df$N) - min(df$N))
# 选择调色板,比如渐变蓝红
col_pal <- colorRampPalette(c("deepskyblue", "darkred"))(100)

# 绘制带垂直线且按N配色的静态3D散点图
scatter3D(x = df$x, y = df$y, z = df$z,
          col = col_pal[cut(df$N_norm, breaks = 100)],
          pch = 16, cex = 1.5,
          # 保留垂直线设置
          panel.first = panel.3Dgrid(col = "gray", lty = 2),
          ticktype = "detailed",
          main = "Static 3D Scatter Plot Colored by N")
# 添加颜色图例
legend("topright", legend = round(seq(min(df$N), max(df$N), length.out = 5)),
       fill = col_pal[round(seq(1, 100, length.out = 5))],
       title = "N Value", cex = 0.8)

二、交互式3D模型(带样本编号标签版本)

如果用plot3D的scatter3Drgl()实现交互,配色逻辑和静态图一致,图例改用rgl包的交互方式添加:

示例代码:

library(plot3D)
library(rgl)

# 归一化N值
df$N_norm <- (df$N - min(df$N)) / (max(df$N) - min(df$N))
# 用viridis调色板(需先安装viridis包)
col_pal <- viridis::viridis(100)

# 绘制交互式3D散点图,按N配色并添加样本标签
scatter3Drgl(x = df$x, y = df$y, z = df$z,
             col = col_pal[cut(df$N_norm, breaks = 100)],
             pch = 16, cex = 1.5,
             type = "s") # type="s"显示球体,也可改为"p"

# 添加样本编号标签
text3d(x = df$x, y = df$y, z = df$z, texts = df$sample_id, adj = c(0.5, 1.5), cex = 0.8)

# 添加交互式颜色图例
legend3d("topright", legend = round(seq(min(df$N), max(df$N), length.out = 5)),
         fill = col_pal[round(seq(1, 100, length.out = 5))],
         title = "N Value", cex = 0.8)

额外说明

  • 若N是分类变量,直接用col = col_pal[as.factor(df$N)]即可,无需归一化
  • 自定义调色板可通过colorRampPalette()任意组合颜色,比如colorRampPalette(c("green", "yellow", "orange"))(50)

内容的提问来源于stack exchange,提问作者Liz L

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 10:18:16