Graphing time-series data when date column doesn&#

2019-08-19 01:45发布

I have the following data:

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

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.

What I did is the following:

  1. Create a column with months jan-dec repeated 5 times
date <- c("Jan", "Feb", "Mär", "Apr", "Mai", "Jun", 
          "Jul", "Aug", "Sep", "Okt", "Nov", "Dez")
date <- rep(date, 5)
  1. Draw graph
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 

2条回答
Viruses.
2楼-- · 2019-08-19 02:14

Try this:

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")
查看更多
地球回转人心会变
3楼-- · 2019-08-19 02:19
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)

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

查看更多
登录 后发表回答