【问题标题】:Multiple time series in ggplot2 from xts object来自xts对象的ggplot2中的多个时间序列
【发布时间】:2016-11-30 13:11:14
【问题描述】:

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

【问题讨论】:

标签: r ggplot2 xts


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    获取所需的图表。

    【讨论】:

      猜你喜欢
      • 2019-09-02
      • 1970-01-01
      • 2020-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-18
      • 2013-04-30
      • 1970-01-01
      相关资源
      最近更新 更多