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

rgl中3D散点图文本与椭球颜色失效及轴刻度移除问题

问题解决:rgl 3D图颜色不生效及移除坐标轴刻度

一、颜色不生效的原因及修复

你的代码中colors[sp]的索引方式错误:sp是物种名称(字符串),而colors是按顺序对应物种水平的向量,用字符串索引会返回NA,导致rgl使用默认颜色(椭球灰色、文本白色)。

修复方式:

在循环中,通过which(levels(peng$species) == sp)获取物种对应的整数位置,用该索引取颜色值。

二、移除坐标轴刻度的方法

先通过plot3d关闭默认坐标轴,再手动添加不带刻度的坐标轴即可。

修改后的完整代码

#' ---
#' title: Penguins data with 3D ellipsoids
#' ---

library(ggplot2)
library(dplyr)
library(tidyr)
library(rgl)
library(stringr) # 补充加载依赖包

data(penguins, package = "palmerpenguins")

penguins <- penguins |>
  drop_na()

#' Select variables
peng <- penguins |>
  select(species, starts_with("bill"), body_mass_g) |>
  rename_with(~ stringr::str_remove(., '_mm$|_g$'))

str(peng)

shapes <- c(15, 17, 18)
colors <- rainbow(3)

colMax <- function(data) sapply(data, max, na.rm = TRUE)

open3d()
par3d(windowRect = c(0, 0, 800, 800) + 50)
rgl.bringtotop()

# 关闭默认坐标轴,手动添加无刻度轴
plot3d(peng[,-1], type = "n", axes = FALSE)
axis3d("x", tick = FALSE)
axis3d("y", tick = FALSE)
axis3d("z", tick = FALSE)

pch3d(peng[,-1],
      pch = shapes[peng$species],
      col = adjustcolor(colors[peng$species], alpha=0.4),
      cex = 0.8, # 调大散点,提升可读性
      decorate = FALSE)

offset <- 0.01
for (sp in levels(peng$species)) {
  xyz <- subset(peng, species == sp)[, 2:4]

# 绘制椭球
  mu <- apply(xyz, 2, mean)
  sigma <- cov(xyz)
  ell <- ellipse3d(sigma, centre = mu, level = 0.68)
  
  sp_idx <- which(levels(peng$species) == sp)
  shade3d(ell, 
          alpha = 0.2, color = colors[sp_idx])

# 添加物种标签
  max <- colMax(xyz)
  max <- max + offset * apply(xyz, 2, diff) # 标签位置偏移,避免重叠
  texts3d(max, adj = 0, text = sp, color = colors[sp_idx], cex = 1.5)
}

额外优化说明

  1. 补充加载stringr包:原代码用到了该包的函数但未显式加载,避免运行报错。
  2. 调整散点和文本大小:原数值过小导致元素模糊,优化后更清晰。
  3. 标签位置偏移:避免标签与椭球、散点重叠,提升图表可读性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 08:25:25