【问题标题】:Is there a way to plot 2 or more series with ggplot2 from an xts object?有没有办法用 ggplot2 从 xts 对象绘制 2 个或更多系列?
【发布时间】:2021-05-28 09:31:44
【问题描述】:

基本上是这里描述的问题Plotting an xts object using ggplot2

但是我不能适应它来绘制两个系列,代码如下:

dates <- c("2014-10-01", "2014-11-01", "2014-12-01", "2015-01-01", "2015-02-01")
values1 <- as.numeric(c(1,2,3,4,5))
values2 <- as.numeric(c(10,9,8,7,6))
new_df <- data_frame(dates, values1, values2)
new_df$dates <- as.Date(dates)
new_df <- as.xts(new_df[, -1], order.by = new_df$dates)

现在我使用 ggplot:

ggplot(new_df, aes(x = Index, y = c(values1, values2))) 
+ geom_point()
   

但我收到以下错误:

错误:美学长度必须为 1 或与数据相同 (5): y 运行rlang::last_error() 以查看错误发生的位置。

这个对象的两个系列可以放在同一个图上吗?

【问题讨论】:

    标签: r ggplot2 xts


    【解决方案1】:

    选项1:将每个系列指定为一个层:

     ggplot(new_df, aes(x = Index)) + 
      geom_point(aes(y = values1, color = "values1")) +
      geom_point(aes(y = values2, color = "values2"))
    

    选项 2:转换为更长的 tibble 形状,以系列名称为列:

    library(tidyverse)
    new_df %>%
      zoo::fortify.zoo() %>%
      as_tibble() %>%
      pivot_longer(-Index, names_to = "series", values_to = "values") %>%
      ggplot(aes(x = Index, y = values, color = series)) + 
      geom_point()
    

    【讨论】:

      【解决方案2】:

      关于 new_df 的创建,我们在最后的注释中修改了计算,给出了相同的值但代码更少:

      • new_df 是一个 xts 对象,而不是 data.frame,所以让我们使用 x 作为更具描述性的名称
      • 创建数据框然后将其转换为 xts 没有任何意义——直接创建一个 xts 对象
      • 我们不需要 as.numeric。 c(...) 的两个实例都已经是数字了。
      • ggplot2 命令采用数据帧,而不是 xts 对象。对于 xts 对象,请改用 autoplot。

      请注意,注释中的x 与问题中的new_df 内容相同。我们刚刚使用了不同的名称。

      现在使用autoplot。如果您想要线条,请省略 the geom="point" 参数,如果您想要单独的面板,请省略 facet=NULL 参数。有关更多示例,请参阅?autoplot.zoo

      library(ggplot2)
      library(xts)
      
      autoplot(x, geom = "point", facet = NULL) + ggtitle("My Plot")
      

      注意

      上面使用的输入。

      library(xts)
      dates <- c("2014-10-01", "2014-11-01", "2014-12-01", "2015-01-01", "2015-02-01")
      values1 <- c(1,2,3,4,5)
      values2 <- c(10,9,8,7,6)
      x <- xts(cbind(values1, values2), as.Date(dates))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-04-17
        • 2012-11-22
        • 2023-04-02
        • 1970-01-01
        • 1970-01-01
        • 2021-02-21
        • 2012-04-27
        • 2020-11-15
        相关资源
        最近更新 更多