Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
291 views
in Technique[技术] by (71.8m points)

How to plot a 3d surface plot using plotly in R?

I have a following dataset:

group<-c(rep("X1",5),rep("X3",5))
set.seed(1)
value<-c(seq(0.2, 1, .2),seq(10, 30, 5))
time<-c("2018-07-01 00:00:00","2018-07-01 01:00:00","2018-07-01 02:00:00","2018-07-01 03:00:00","2018-07-01 04:00:00",
        "2018-07-01 00:00:00","2018-07-01 01:00:00","2018-07-01 03:00:00","2018-07-01 04:00:00","2018-07-01 05:00:00")
order<-c(1,2,3,4,5,1,2,4,5,6)
country<-c("HU","ZA","XX","ZZ","RO","HU","ZA","XX","ZZ","RO")
dat <-data.frame(time,country,group,value,order)

I want to plot a 3d plot where x=order, Y=value, z=hour(time). I read here that z should have dimension [x,y]. 3d Surface Plot in R with plotly 4 Something like this one should be obtained:

enter image description here

How can I plot this, because do not understand how can I create a matrix for Z with this dimension?

question from:https://stackoverflow.com/questions/65942132/how-to-plot-a-3d-surface-plot-using-plotly-in-r

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your data doesn't seem suited for 3D. You can't have two values for z with the same x and y-axis. If you filter out one of the groups you can technically make it work, but I think some other chart would work better. Here's an example of how you could make it work with one group and an example of a plot that may work better.

library(plotly)

group<-c(rep("X1",5),rep("X3",5))
set.seed(1)
value<-c(seq(0.2, 1, .2),seq(10, 30, 5))
time<-c("2018-07-01 00:00:00","2018-07-01 01:00:00","2018-07-01 02:00:00","2018-07-01 03:00:00","2018-07-01 04:00:00",
        "2018-07-01 00:00:00","2018-07-01 01:00:00","2018-07-01 03:00:00","2018-07-01 04:00:00","2018-07-01 05:00:00")
order<-c(1,2,3,4,5,1,2,4,5,6)
country<-c("HU","ZA","XX","ZZ","RO","HU","ZA","XX","ZZ","RO")
dat <-data.frame(time,country,group,value,order)

library(tidyverse)
m = dat %>%
  filter(group == "X1") %>% 
  pivot_wider(c(time,value,order), names_from = time,
                    values_from = value) %>% 
  select(-order) %>%
  as.matrix
m[] = case_when(is.na(m) ~ 0, TRUE ~ m)
plot_ly(z = ~m) %>% 
  add_surface()

plot_ly(data = dat, x = ~time, y = ~value, color = ~group)

This is an example of data that is better suited

m = matrix(rnorm(25),nrow = 5, ncol = 5)

plot_ly(z = ~m) %>% 
  add_surface()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...