Line-chart of time-series data with monthly labels

2019-07-27 00:13发布

问题:

I have the following data:

library(dplyr)
    set.seed(122)
    df <- as_tibble(rlnorm(1260, meanlog = 0.06, sdlog = 0.20))
date <- rep(c("Jan", "Feb", "Mär", "Apr", "Mai", "Jun", 
      "Jul", "Aug", "Sep", "Okt", "Nov", "Dez"), 5)

These are supposed to be 1260 daily prices with one year = 252 days and 1 month = 21 days.

Now, I want to draw a line-chart with the daily prices on the y-axis and months on the x-axis. The code below is adapted form this thread Graphing time-series data when date column doesn't exist:

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)

However, I slightly changed my df by inserting a new first row with value 1.

df <- rbind(df[0,],c(1),df[1:nrow(df),])

This is supposed to be the starting price at t=0. Unfortunately, the code doesn't work out now. Is there a quick fix for this?

回答1:

library(tidyverse)

df %>%
  as.data.frame() %>%
  rename(price = 1) %>% 
  mutate(rnames = rownames(.)) %>% 
  ggplot(aes(x = as.numeric(rnames)-1, y = price, 
             group = c(1,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)

You can also add a new breakpoint for point 0. by changing like scale_x like this:

scale_x_continuous(breaks = c(0, seq(1, 1260, by = 21)), labels = c("t=0", date))

If you still want the datapoint with price == 1 (your new row) be labeled as Jan then you don't need to subtract 1 from your x in the aesthetics and your breaks don't need to be manipulated. It works either way.

The most important thing to get my previous code to work with your new dataframe is changing the group in the aesthetics to be the same size as your new dataframe.



标签: r ggplot2 plot