在日期列不存在时绘制时间序列数据

时间:2019-05-27 16:13:28

标签: r ggplot2 time-series

我有以下数据:

set.seed(12)
df <- rnorm(1260, 0.06, 0.2)

这些是5年的日收益(1年= 252个工作日),我想做的是在x轴上画一个折线图。基本上,我将让Jan:Dec序列在x轴上重复五次,其中21天为一个月。

我的工作如下:

  1. 创建一个列,其中jan-dec月份重复5次
date <- c("Jan", "Feb", "Mär", "Apr", "Mai", "Jun", 
          "Jul", "Aug", "Sep", "Okt", "Nov", "Dez")
date <- rep(date, 5)
  1. 绘制图形
df %>%
       ggplot(aes(x = date, y = return)) +
       geom_line() +
       labs(title = "Stock return Chart", y = "return", x = "date")

不幸的是,我收到以下错误消息:

 Error: Aesthetics must be either length 1 or the same as the data (1260): x 

2 个答案:

答案 0 :(得分:2)

library(tidyverse)

df %>%
    as.data.frame() %>%
    rename(price = 1) %>% 
    mutate(rnames = rownames(.)) %>% 
    ggplot(aes(x = as.numeric(rnames), y = price, 
                group = rep(1:5, times=1, each=252))) +
      geom_line() +
      labs(title = "Stock Price Chart", y = "Price", x = "date") +
      scale_x_continuous(breaks = seq(1, 1260, by = 21), labels = date)

![](https://i.imgur.com/jR6C8rI.png)

reprex package(v0.3.0)于2019-05-27创建

答案 1 :(得分:0)

尝试一下:

price <- rnorm(1260, 0.06, 0.2)

date.base <- c("Jan", "Feb", "Mär", "Apr", "Mai", "Jun", 
          "Jul", "Aug", "Sep", "Okt", "Nov", "Dez")
date <- rep(date.base, 5)

data.frame(date=factor(date, ordered=TRUE, levels=date.base), price=price) %>%
  ggplot(aes(x = date, y = price)) +
  geom_line() +
  labs(title = "Stock Price Chart", y = "Price", x = "date")