2

I saw this 3D picture the other day in a journal that describes the evolution over time of Birth Rates between 1980-1999 by age. The vertical line is the birth rates. The two horizontal lines are, age, and year.

enter image description here

I really would like to reproduce one like this. I can imagine the data would look something like (simplified)

dta = cbind(c(2000, 2005, 2015), 
  c(15, 20, 25), 
  c(20, 24, 35))

colnames(dta) <- c('year', 'age', 'rate')

 year age rate
 2000  15   20
 2005  20   24
 2015  25   35

I searched for some 3D libraries and package plot3D came out. I tried to figure out how the function outer() works but I couldn't understand!

Do you have any ideas how I could reproduce a 3D plot like the one above?

Werner Hertzog
  • 2,002
  • 3
  • 24
  • 36
giac
  • 4,261
  • 5
  • 30
  • 59

2 Answers2

0

Try this:

library(graphics)
dta = cbind(c(2000, 2005, 2015), 
        c(15, 20, 25), 
        c(20, 24, 35))

colnames(dta) <- c('year', 'age', 'rate')
dta = as.data.frame(dta)
persp(dta$year, dta$age, matrix(runif(9),3,3), theta = 30, phi = 30, expand = 0.5, col = "lightblue",
      ltheta = 120, shade = 0.75, ticktype = "detailed",
      xlab = "year", ylab = "age", zlab = "rate")

Ref: demo(persp) in R

Note: The thirs argument (z) must be a matrix

user1436187
  • 3,252
  • 3
  • 26
  • 59
  • I got an error from your example **Error in persp.default(dta$year, dta$age, dta$rate, theta = 30, phi = 30, : invalid 'z' argument** – giac Jun 18 '15 at 12:13
  • Check if `class(dta$rate)` is a factor. – user1436187 Jun 18 '15 at 12:14
  • **Error in if (any(diff(x) <= 0) || any(diff(y) <= 0)) stop("increasing 'x' and 'y' values expected") : missing value where TRUE/FALSE needed In addition: Warning messages: 1: In Ops.factor(diff(x), 0) : '<=' not meaningful for factors 2: In Ops.factor(diff(y), 0) : '<=' not meaningful for factors** – giac Jun 18 '15 at 12:20
  • could you post the plot you get ? – giac Jun 18 '15 at 12:20
  • You are right `z` must be a matrix. Each element in the matrix shows the hight of the points in the surface. You need more values to create a surface. – user1436187 Jun 18 '15 at 12:26
0

I prefer the plot3d function from "rgl" package. Since you just have a few point, I adjusted the limits so that you can see them.

library("rgl") plot3d(dta, xlim=c(1990, 2030), ylim=c(10,30), zlim=c(15,40))

Ivo Fugers
  • 109
  • 5