使用 ts.plot 绘制每日时间序列

问题描述 投票:0回答:1

我正在尝试使用

ts.plot
来绘制每日时间序列。由于默认刻度标签并不是特别有意义,因此我尝试先抑制 x 轴,然后再添加自定义轴:

library(quantmod)
getSymbols("MSFT", src = "yahoo", from = "2023-01-01", to = "2023-12-31")
msft_prices <- as.numeric(Cl(MSFT))
ts_msft <- ts(msft_prices, frequency = 365, start = c(2023, 1))
plot.ts(ts_msft, ylab = "stock price", xlab = "days", xaxt = "n")
date_labels <- seq(as.Date("2023-01-01"), by = "1 month", length.out = 12)
x_indices <- seq(1, length(ts_msft), length.out = length(date_labels))
axis(1, at = x_indices, labels = format(date_labels, "%b %d"), las = 2)

不幸的是,新的 x 轴未打印。有谁明白这是为什么吗?谢谢一百万。

r plot
1个回答
0
投票

x 轴位置是十进制日期而不是简单的整数序列。您可以使用

lubridate::decimal_date
:

将所选日期转换为十进制日期
library(quantmod)
library(lubridate)

getSymbols("MSFT", src = "yahoo", from = "2023-01-01", to = "2023-12-31")
msft_prices <- as.numeric(Cl(MSFT))
ts_msft <- ts(msft_prices, frequency = 365, start = c(2023, 1))
plot.ts(ts_msft, ylab = "stock price", xlab = "", xaxt = "n")
date_labels <- seq(as.Date("2023-01-01"), by = "1 month", length.out = 12)
x_indices <- decimal_date(date_labels)
axis(1, at = x_indices, labels = format(date_labels, "%b %d"), las = 2)

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.