Search code examples
rcolorsellipsergl

Color of text and ellipses not working in rgl


I have a simple 3D scatter plot in rgl where I want to add data ellipsoids and text labels, but I can't get colors to work. The ellipsoids appear in grey, and the text labels appear in white.

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

library(ggplot2)
library(dplyr)
library(tidyr)
library(rgl)

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)
shapes <- 1:3
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")
pch3d(peng[,-1],
      pch = shapes,
      col = adjustcolor(colors[peng$species], alpha=0.4),
      cex = 0.1,
      decorate = FALSE)

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

# ellipsoids
  mu <- apply(xyz, 2, mean)
  sigma <- cov(xyz)
  ell <- ellipse3d(sigma, centre = mu, level = 0.68)

  shade3d(ell, 
          alpha = 0.2, color = colors[sp])

# find location to label the ellipse
  max <- colMax(xyz)
  bbox <- matrix(rgl::par3d("bbox"), nrow=2)
  ranges <- apply(bbox, 2, diff)
  texts3d(max, adj = 0, text = sp, color = colors[sp], cex = 3)
}

Here's what I get: enter image description here

Also, how can I remove the tick marks on the axes?


Solution

  • You forgot:

    names(colors) <- levels(peng$species)
    

    So you have some NA colors.

    enter image description here