3D scatter plot with data points colored according to their group

I want to make a 3D scatter plot as shown in this image. However, my code is just showing an empty cube with no data points. Any help in this regard would be highly appreciated. Here is my code, it can be run in the R studio:

library(dplyr)
library(plotly)
library(plyr)
library("scatterplot3d")
library(rgl)
#Code for 3D Scatter Plot
collarid <- c("cattle12", "cattle12", "cattle17","cattle19", "cattle17", 
"cattle19", "cattle12", "cattle13","cattle13", "cattle14", "cattle14", 
"cattle15", "cattle15" )
longitude <- c(11.1, 11.2, 11.3, 11.4, 11.5, 11.6, 11.7, 11.8, 11.9, 12.0, 
12.1, 12.2, 12.3)
latitude<-c(15.67, 15.7, 15.8, 15.9, 16.0, 16.1, 16.2, 16.3, 16.4, 16.5, 
16.6, 16.7, 16.8)
height<-c(302.9, 301.6, 300.5, 303.2, 304.8, 305.8, 302.1, 310.8, 375.6, 
200.9, 234.5, 216.7, 211.8)
df <- data.frame(collarid, latitude, longitude, height)
df_uniq <- unique(df$collarid)
x<-length(df_uniq)
scatterplot3d(df$longitude,df$latitude,df$height,pch=20, color=rainbow(x) 
[df$collarid])

threedscattergroups_g

I find evaluating intermediate steps to be useful. In this case, ask R what it thinks of your two-step color statement:

rainbow(x)[df$collarid]
 [1] NA NA NA NA NA NA NA NA NA NA NA NA NA

A type change is required as rainbow doesn't have a name vector that corresponds to cattle#. Turning it into a factor passes numbers that resolve.

> rainbow(x)[as.factor(df$collarid)]
 [1] "#FF0000" "#FF0000" "#0000FF" "#FF00FF" "#0000FF" "#FF00FF" "#FF0000" "#FFFF00" "#FFFF00" "#00FF00"
[11] "#00FF00" "#00FFFF" "#00FFFF"

This should solve your problem.

scatterplot3d(df$longitude,df$latitude,df$height,pch=20, color=rainbow(x)[as.factor(df$collarid)])
1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.