rggplot2chartssurface

Surface chart from time series in R


Can a surface chart be created directly from a time series of daily data in R?

That surface would have months as x-axis, years as y-axis and values in the z-axis.

dt <- seq(as.Date('2006-01-01'),as.Date('2020-01-31'),by = 1)
temp <- rnorm(5144, mean=21, sd=5)

df <- data. Frame(dt, temp)

Solution

  • If you're looking for a 3D surface plot, you can convert to matrix format and plot with plotly

    dt   <- seq(as.Date('2006-01-01'), as.Date('2020-12-31'), by = 1)
    temp <- rnorm(length(dt), mean = 21, sd = 5)
    df   <- data.frame(dt, temp)
    
    library(plotly)
    
    df$month <- as.numeric(substr(df$dt, 6, 7))
    df$year <- as.numeric(substr(df$dt, 1, 4))
    df <- aggregate(temp ~ year + month, data = df, mean)
    m <- matrix(df$temp, ncol = 12)
    dimnames(m) <- list(sort(unique(df$year)), sort(unique(df$month)))
    
    plot_ly(z = ~m) |> add_surface() |> 
      layout(scene = list(yaxis = list(title = "Year", tickvals = 0:14,
                                       ticktext = 2006:2020),
                          xaxis = list(title = "Month", tickvals = 0:11,
                                       ticktext = month.abb),
                          zaxis = list(title = "Temperature")))
    

    enter image description here