【发布时间】:2016-11-30 13:11:14
【问题描述】:
我有一个 XTS 对象,我想在 ggplot 中绘制几个时间序列。如何在同一个图中绘制多个时间序列?
【问题讨论】:
-
欢迎来到 StackOverflow。请采取tour 并观察ask 的内容和方式。如果您的问题是关于代码的,请提供minimal, complete and verifiable example 说明您目前所做的工作。
我有一个 XTS 对象,我想在 ggplot 中绘制几个时间序列。如何在同一个图中绘制多个时间序列?
【问题讨论】:
由于您没有提供任何数据集,我将使用AirPassengers 数据集举例说明:
library(datasets)
library(xts)
library(ggplot2)
library(broom)
library(magrittr)
ap.xts <- as.xts(AirPassengers)
mseries <- cbind(ap.xts, rollmean(ap.xts,7)) # mseries is a xts object with multiple variables
names(mseries) <- c("Passengers", "MA_Passengers") # names for the series, otherwise the names are '..1' and '..2'
index(mseries) <- as.Date(index(mseries)) # to avoid warnings since ggplot scale don't handle yearmon natively
tidy(mseries) %>% ggplot(aes(x=index,y=value, color=series)) + geom_line()
【讨论】:
作为@RubenLaguna 方法的替代方案,您可能更喜欢简洁的autoplot.zoo:
#Borrowing the set-up from RubenLaguna:
library(xts)
library(ggplot2)
ap.xts <- as.xts(AirPassengers)
mseries <- cbind(ap.xts, rollmean(ap.xts,7)) # mseries is a xts object with multiple variables
names(mseries) <- c("Passengers", "MA_Passengers") # names for the series, otherwise the names are '..1' and '..2'
现在最简单的 IMO 操作:
autoplot.zoo(mseries, facets=NULL)
获取所需的图表。
【讨论】: