在日期列不存在时绘制时间序列数据 [英] Graphing time-series data when date column doesn't exist

查看:48
本文介绍了在日期列不存在时绘制时间序列数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数据:

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

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

These are 5 years worth of daily returns (with 1 year = 252 working days) and what I would like to do is draw a line-chart with months on the x axis. Basically, I would have the sequence Jan:Dec repeated five times on the x-axis, with 21 days being one month.

我所做的是以下事情:

  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")

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

Unfortunately I get the following error:

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

推荐答案

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)

reprex包(v0.3.0)于2019-05-27创建sup>

Created on 2019-05-27 by the reprex package (v0.3.0)

这篇关于在日期列不存在时绘制时间序列数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆