2016-07-26 84 views
-1

我有一個XTS對象,我想從它繪製一個ggplot中的幾個時間序列。我如何在同一個情節中繪製多個時間序列?從xts對象ggplot2中的多個時間序列

+2

歡迎StackOverflow上。請參考[遊覽](http://stackoverflow.com/tour)並觀察[問](http://stackoverflow.com/help/asking)的內容和方式。如果您的問題與代碼有關,請提供迄今爲止所做的工作[最簡單,完整且可驗證的示例](http://stackoverflow.com/help/mcve)。 – user3078414

回答

2

既然你不提供任何數據集,我將舉例說明使用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