1

I am trying to plot date, x and y in a 3D plot in R. (Using RStudio 0.99.903), R (3.3.2), scatterplot3d(0.3-40), rgl(0.98.1)

dates = c("2016-11-10","2016-11-20","2016-12-01","2016-12-15","2016-12-30")

x = rnorm(5,0,1)

y = rnorm(5,1,2)

A = data.frame(dates, x, y)

A$dates = as.Date(A$dates,"%yyyy-%mm-%dd")

library(scatterplot3d)

with(data=A, scatterplot3d(x=x,y=y,z=dates))

This plots the dates as integers

I also tried the rgl package, but get the same result.

library(rgl)

plot3d(x=A$x,y=A$y,z=A$dates)
M--
  • 25,431
  • 8
  • 61
  • 93
Susan
  • 11
  • 3

2 Answers2

1

Read about how to use as.Date. You need to format date appropriately and you get your desired plot:

     dates = c("2016-11-10","2016-11-20","2016-12-01","2016-12-15","2016-12-30")
     x = rnorm(5,0,1)
     y = rnorm(5,1,2)
     A = data.frame(dates, x, y)

     A$dates = as.Date(A$dates,"%Y-%m-%d")
     
     library(scatterplot3d)
     
     scatterplot3d(x=A$x, y=A$y, z=A$dates)

Plot would look like:

enter image description here

To correct the z-axis you can refer to this page.

To avoid these mistakes you can use anytime package by Dirk Eddelbuettel.

library(anytime)
A$dates <- anytime(A$dates) 
M--
  • 25,431
  • 8
  • 61
  • 93
1

Masoud showed you how to convert the character strings to dates. To get nice date labels in rgl, you'll need to do a little extra work yourself: it doesn't know anything about dates. For example,

 dates = c("2016-11-10","2016-11-20","2016-12-01","2016-12-15","2016-12-30")
 x = rnorm(5,0,1)
 y = rnorm(5,1,2)
 A = data.frame(dates, x, y)


 A$dates = as.Date(A$dates,"%Y-%m-%d")

 ticks <- pretty(A$dates)
 plot3d(A$x, A$y, A$dates, axes = FALSE)
 box3d()
 axes3d(c("x", "y")) # default axis labels here
 axis3d("z", at = ticks, 
   labels = format(ticks, format = "%b %d")) # see ?strptime for formats

I'm not sure if these labels are possible in scatterplot3d.

user2554330
  • 37,248
  • 4
  • 43
  • 90