我有以下数据:
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轴上绘制月份的折线图。下面的代码是从该线程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)
但是,我通过插入值df
的新第一行来稍微更改了1
。
df <- rbind(df[0,],c(1),df[1:nrow(df),])
这应该是t = 0时的起始价格。不幸的是,该代码现在无法解决。有快速解决方案吗?
答案 0 :(得分: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
的{{1}}中减去x
美学和您的休息不需要操纵。无论哪种方式都可以。
使我先前的代码与新数据框一起使用的最重要事情是将美观上的group
更改为与新数据框相同的大小。