Search code examples
rplotstldplyrggvis

Plot LOESS (STL) decomposition using Ggvis


I want to be able to plot the three different elements of The Seasonal Trend Decomposition using Loess (STL) with Ggvis.

However, I recive this error:

Error: data_frames can only contain 1d atomic vectors and lists

I am using the nottem data set.

# The Seasonal Trend Decomposition using Loess (STL) with Ggvis
# Load nottem data set
library(datasets)
nottem <- nottem

# Decompose using stl()
nottem.stl = stl(nottem, s.window="periodic")

# Plot decomposition
plot(nottem.stl)

Now, this is the information I am interested in. In order to make this into a plot that I can play around with I transform this into a data frame using the xts-package. So far so good.

# Transform nottem.stl to a data.frame
library(xts)
df.nottem.stl <- as.data.frame(as.xts(nottem.stl$time.series))

# Add date to data.frame
df.nottem.stl$date <- data.frame(time = seq(as.Date("1920-01-01"), by = ("months"), length =240))

# Glimpse data
glimpse(df.nottem.stl)

# Plot simple line of trend
plot(df.nottem.stl$date, df.nottem.stl$trend, type = "o")

enter image description here

This is pretty much the plot I want. However, I want to be able to use it with Shiny and therefore Ggvis is preferable.

# Plot ggvis
df.nottem.stl%>%
  ggvis(~date, ~trend)%>%
  layer_lines()

This is where I get my error.

Any hints on what might go wrong?


Solution

  • First of all your df.nottem.stl data.frame contains a Date data.frame, so you should be using the date$time column. Then using the layer_paths function instead of the layer_lines will make it work. I always find layer_paths working better than layer_lines:

    So this will work:

    library(ggvis)
    df.nottem.stl%>%
      ggvis(~date$time, ~trend)%>%
      #for points
      layer_points() %>% 
      #for lines
      layer_paths()
    

    Output:

    enter image description here