Boram Lim
Boram Lim

Reputation: 323

How can I make 3d plot with stacked 2d plot?

I want to plot as below. I tried to search several packages and plot functions but I couldn't find a solution.

My data has four columns.

ID  F  R  M
 1  2  3  4
 2  4  6  7
...

I want to see the relationship between M and R with respect to each F value (1, 2, 3, ...). So, I'd like F along the x-axis, R along the y-axis, and M as the z-axis as in the below graph.

Thanks.

enter image description here

Upvotes: 1

Views: 1828

Answers (1)

jbaums
jbaums

Reputation: 27408

You can do this kind of thing with lattice cloud plots, using panel.3dpolygon from latticeExtra.

library(latticeExtra)

# generating random data
d <- data.frame(x=rep(1:40, 7), y=rep(1:7, each=40), 
                z=c(sapply(1:7, function(x) runif(40, 10*x, 10*x+20))))

# define the panel function
f <- function(x, y, z, groups, subscripts, ...) {
  colorz <- c('#8dd3c7', '#ffffb3', '#bebada', '#fb8072', '#80b1d3', 
              '#fdb462', '#b3de69')
  sapply(sort(unique(groups), decreasing=TRUE), function(i) {
    zz <- z[subscripts][groups==i]
    yy <- y[subscripts][groups==i]
    xx <- x[subscripts][groups==i]    
    panel.3dpolygon(c(xx, rev(xx)), c(yy, yy), 
                    c(zz, rep(-0.5, length(zz))), 
                    col=colorz[i], ...)
  })

}

# plot
cloud(z~x+y, d, groups=y, panel.3d.cloud=f, scales=list(arrows=FALSE))

I'm sure I don't need to loop over groups in the panel function, but I always forget the correct incantation for subscripts and groups to work as intended.

As others have mentioned in comments, this type of plot might look snazzy, but can obscure data.

enter image description here

Upvotes: 4

Related Questions