时间序列数据的折线图,x轴为每月标签,y轴为每日数据 [英] Line-chart of time-series data with monthly labels on x-axis but daily data on y-axis

查看:73
本文介绍了时间序列数据的折线图,x轴为每月标签,y轴为每日数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数据:

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天.

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

现在,我想在y轴上绘制每日价格,在x轴上绘制月份的折线图.下面的代码是从该线程改编的

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)

但是,我通过插入新的第一行,其值为 1 来略微更改了 df .

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),])

这应该是t = 0时的起始价格.不幸的是,该代码现在无法解决.有快速解决方法吗?

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?

推荐答案

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 :

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

如果您仍然希望将 price == 1 (新行)的数据点标记为 Jan ,则无需减去 1 从您的 x 的美学角度出发,您的休息时间无需操纵.无论哪种方式都可以.

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.

使我以前的代码与新数据框一起使用的最重要事情是,将外观上的 group 更改为与新数据框相同的大小.

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.

这篇关于时间序列数据的折线图,x轴为每月标签,y轴为每日数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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