Search code examples
rplotscatter3d

Convert 3D scatter plots to 3D linear plots and separate based on the colours


I have been struggling to plot a 3D chart in R for a while. I think I am very close to what I want. I have asked a question before. What I need to know now is only how to convert the scatterplots with dots to linear. I mean if only I can connect the points it is great for me. What I have now looks like below: enter image description here I need to connect the points which has a better view in 3D. I need a separate line for each color and I want to add legend to the chart.

I have defined my data as:

df <- data.frame(a1 = c(489.4,  505.8,  525.8,  550.2,  576.6),
a2 = c(197.8,  301,    389.8,  502,    571.2),
b1 = c(546.8,  552.6,  558.4,  566.4,  575),
b2 = c(287.2,  305.8,  305.2,  334.4,  348.6), c1 = c(599.6,  611.4,  
623.6,  658,    657.4), c2 = c(318.8,  423.2,  510.8,  662.4,  656),
d1 = c(616,    606.8,  600.2,  595.6,  595),
  d2 = c(242.4,  292.8,  329.2,  378,    397.2),
e1 = c(582.4,  580,    579,    579,    579),
e2 = c(214,    255.4,  281.8,  303.8,  353.8))

colnames(df) <- rep(c("V1", "V2"), 5)
df.new <- rbind(df[, c(1, 2)],df[, c(3, 4)],df[, c(5, 6)],               
df[, c(7, 8)],df[, c(9, 10)])
df.new$Group <- factor(rep(c("a","b","c","d","e"), each = 5))
df.new$Class <- rep(c(1:5), 5)
x=df.new$Class
y=V1
z=V2

Below is my code:

 library(scatterplot3d)  #colors
 colors <- c("#999999", "#E69F00", "#56B4E9","#1B9E77", "#D95F02")
 colors <- colors[as.numeric(df.new$Group)]#Others
 xlabs <- c("[7,9]", "[10,12]", "[16,18]", "[19,21]", "[22,24]")
 scatterplot3d(x,y,z, pch = 16, color=colors,main="Title",xlab 
 ="Intervals",ylab = "", zlab = "Total time",     x.ticklabs=xlabs)
 text(8, 2.4, "c",cex = 1)
 text(9, 2, "c",cex = 1)

I really appreciate if someone can help me about this issue that I have been struggling. I know there is a type=1 but it makes just one unified plot.


Solution

  • Try this:

    sd<-scatterplot3d(x,y,z, pch = rep(16:12, each=5), color=colors,main="Title",xlab 
                      ="Intervals",ylab = "", zlab = "Total time", x.ticklabs=xlabs)
    sd$points3d(x[1:5],y[1:5],z[1:5], col="purple", type="l")
    sd$points3d(x[6:10],y[6:10],z[6:10], col="orange", type="l")
    sd$points3d(x[11:15],y[11:15],z[11:15], col="blue", type="l")
    sd$points3d(x[16:20],y[16:20],z[16:20], col="green", type="l")
    sd$points3d(x[21:25],y[21:25],z[21:25], col="red", type="l")
    legend("right", legend = levels(df.new$Group), col= levels(as.factor(colors)),pch = rep(16:12, each=1))