使用Ggvis绘制LOESS(STL)分解

时间:2015-10-22 14:29:46

标签: r plot stl dplyr ggvis

我希望能够使用黄土(STL)和Ggvis绘制季节性趋势分解的三个不同元素。

但是,我发现了这个错误:

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

我正在使用nottem数据集。

# 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)

现在,这是我感兴趣的信息。为了使这成为我可以玩的图,我使用xts-package将其转换为数据框。到目前为止一切都很好。

# 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

这几乎是我想要的情节。但是,我希望能够将它与Shiny一起使用,因此Ggvis更受欢迎。

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

这是我收到错误的地方。

任何可能出错的提示?

1 个答案:

答案 0 :(得分:2)

首先,您的df.nottem.stl data.frame包含Date data.frame,因此您应该使用date$time列。然后使用layer_paths函数代替layer_lines将使其正常工作。我总觉得layer_pathslayer_lines更好地工作:

所以这会奏效:

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

输出:

enter image description here