Hi all!
I have some stable isotopes data for around 250 individuals that are contained in 13 different sites.
I want to use Plotly to create a 3D plot showing my 3D isotopic niche with all my samples, along with my 13 ellipsoids representing each of my site. I want the Ellipsoids to be of the color I mentionned at the beginning of my code, as well as the points (samples). However, I got quite a patchy color for all my ellipsoids, not homogenous, and my points are not of the same color as the sites. I tried different stuffs, but I keep getting the same output.
Is someone able to help me with this? It would be a biiiiggg relief.
Thanks for reading this!
Manon
The code:
library(plotly)
library(dplyr)
Custom colors
color ← c(“#a6cee3”, “#1f78b4”, “#b2df8a”, “#33a02c”, “#fb9a99”, “#e31a1c”,
“#fdbf6f”, “#ff7f00”, “#cab2d6”, “#6a3d9a”, “#ffff99”, “#e5d8bd”, “#c51b7d”)
Convert HEX to RGB strings for mesh3d (required for uniform facecolor)
hex_to_rgb ← function(hex) {
rgb ← grDevices::col2rgb(hex)
sprintf(“rgb(%d,%d,%d)”, rgb[1], rgb[2], rgb[3])
}
rgb_colors ← sapply(color, hex_to_rgb)
Get unique sites
sites ← unique(spdata$site)
Start plot
plot ← plot_ly()
for (i in seq_along(sites)) {
site ← sites[i]
data_points ← filter(spdata, site == site)
ellipsoid_vertices ← vertices_by_site[[as.character(site)]]
hex ← color[i]
rgb ← rgb_colors[i]
Add points
plot ← plot %>%
add_trace(
x = data_points$d13C,
y = data_points$d15N,
z = data_points$d34S,
type = “scatter3d”,
mode = “markers”,
marker = list(size = 4, color = hex),
name = paste(“Site”, site),
showlegend = TRUE,
legendgroup = site
)
Add ellipsoid mesh
plot ← plot %>%
add_trace(
type = “mesh3d”,
x = ellipsoid_vertices$d13C,
y = ellipsoid_vertices$d15N,
z = ellipsoid_vertices$d34S,
i = seq(1, nrow(ellipsoid_vertices)-2, by=3),
j = seq(2, nrow(ellipsoid_vertices)-1, by=3),
k = seq(3, nrow(ellipsoid_vertices), by=3),
facecolor = rep(rgb, length.out = nrow(ellipsoid_vertices)/3), # uniform color
opacity = 0.2,
name = paste(“Site”, site), # same name as above
showlegend = FALSE, # don’t show legend again
legendgroup = site
)
}
Final layout
plot ← plot %>%
layout(
scene = list(
xaxis = list(title = “δ15N”),
yaxis = list(title = “δ13C”),
zaxis = list(title = “δ34S”)
),
title = “Ellipsoids of isotopic niche by site”
)
plot