13

I'm wanting to create a ribbon plot (really it's a line plot of multiple groups of a categorical variable) but displayed in a 3d style. This would look something like this:

Ribbon plot example

So maybe we would want to plot the following sample data as a ribbon plot:

set.seed(10)
fun <- function(i) data.frame(person=rep(LETTERS[i], 26), 
    letter=letters, count=sample(0:100, 26, T))
dat <- do.call(rbind, lapply(1:10, function(i) fun(i)))

library(ggplot2) #a traditional 2-d line plot of the data
ggplot(data=dat, aes(x=letter, y=count, group=person, color=person)) + 
    geom_line()

How can this be achieved in R? I know there may be better ways to display the data but my interest currently is in producing the ribbon style plot.

1 Answer 1

18

Hopefully the example below will help point you in the right direction:

# data
mat <- matrix(dpois(rep(1:20, 10), lambda=rep(10:1, each=20)), ncol=10)

# 2d line plot
matplot(mat, type="l", col="black", lty=1)

# 3d ribbon plots
par(mar = c(0, 1, 0, 1))
par(mfrow=c(1,2))
persp(z=mat[,rep(seq(ncol(mat)), each=2)], r=5, theta=320, phi=35, shade=0.5,
      border=NULL, col=rep(c("#808080FE","#00000000"), each=nrow(mat)-1))
persp(z=mat[,rep(seq(ncol(mat)), each=2)], r=5, theta=320, phi=35, shade=0.5,
      border=NA, col=rep(c("#808080FE","#00000000"), each=nrow(mat)-1))
par(mfrow=c(1,1))
par(mar = c(5,4,4,2)+.1)

ribbon_example

As you can see, the basic idea here is pretty simple. We organize our values to be plotted into a matrix, duplicate the columns in the matrix so that they are in pairs, and then plot the values using persp(), making sure to alternate between transparent and opaque colors. However, there are a few tricky details that remain to be worked out, particularly regarding what to do with the border parameter. I will leave those details to you.

Hope this helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.