Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

plot

r

plotly

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?

like image 978
Erko Tru Avatar asked Feb 16 '26 14:02

Erko Tru


1 Answers

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()
like image 112
bischrob Avatar answered Feb 18 '26 06:02

bischrob



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!