时间序列数据的线路图与x轴每月标签,但在y轴上的每日数据(Line-chart of time-se

2019-09-28 01:13发布

我有以下数据:

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)

这些都应该是每天1260倍的价格用一年时间= 252天和1月= 21天。

现在,我想画一个线图与日常价格在y轴个月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)

不过,我略微改变了我的df通过插入一个新的第一行与值1

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

这被认为是在t = 0的起始价格。 不幸的是,代码现在不工作了。 是否有一个快速修复这个?

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

您还可以添加新的断点点0 。 通过改变像scale_x是这样的:

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

如果你还是想用数据点price == 1 (新行)被标为Jan那么你并不需要减去1从您的x在美学和你的休息不需要进行操作。 它仍然可以正常工作。

最重要的事情,让我以前的代码与新的数据框正在改变工作group在美学是大小作为新的数据帧相同。



文章来源: Line-chart of time-series data with monthly labels on x-axis but daily data on y-axis
标签: r ggplot2 plot