来自xts对象的ggplot2中的多个时间序列

时间:2016-07-26 18:34:21

标签: r ggplot2 xts

我有一个XTS对象,我想在ggplot中绘制几个时间序列。如何在同一个图中绘制多个时间序列?

2 个答案:

答案 0 :(得分:3)

由于您没有提供任何数据集,我将举例说明使用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()

multiple xts in ggplot2

答案 1 :(得分:0)

作为@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)

获取所需的图形。