R:向时间序列图添加垂直虚线

46scxncf  于 2023-03-27  发布在  其他
关注(0)|答案(2)|浏览(125)

我在R中做了如下的图:

# Generate weekly sales time series from 2000-01-01 to 2020-01-01
set.seed(123)
sales <- ts(rnorm(1040, mean = 100, sd = 50), start = c(2000, 1), frequency = 52)

  # Plot the time series with a vertical line at January 1, 2010
    plot.ts(sales, main = "Weekly Sales", xlab = "Date", ylab = "Sales", col = "blue", ylim = c(0, max(sales)*1.1))

**我的问题:**我试图在2010-01-01处添加一条红色的垂直虚线。我尝试使用以下代码来完成此操作:

abline(v = as.numeric(as.Date("2010-01-01")), lty = "dotted", lwd = 2, col = "red")

我看不见线-我试着改变厚度,但我还是看不见。
有人能告诉我如何正确地做吗?
谢谢!

5n0oy7gb

5n0oy7gb1#

这条线没有出现在图上的原因是plot.ts()使用公元前的整年作为时间单位,而as.numeric(as.Date())的输出是以Unix time为单位(即从00:00:00 UTC 1970-01-01开始的秒):

> as.numeric(as.Date("2010-01-01"))
[1] 14610

你的问题的解决方案是对初始图和abline()使用相同的时间单位。这就是ggplot中建议解决方案的另一个答案。如果你宁愿坚持以R为基数,@tpetzoldt的评论有一个简单的方法来获得你想要的:

abline(v = 2010, lty = "dotted", lwd = 2, col = "red")

适用于2010-01-01。如果您需要更精细的时间分辨率,请首先计算一年中的第几天,除以365并将其用作小数。lubridate使其非常简单:

mydate <- as.Date('2010-06-06')
abline(v = lubridate::year(mydate) + lubridate::yday(mydate)/365,
       lty = "dotted", lwd = 2, col = "red")

或者更好:使用lubridate::decimal_date()

完整答案:

# Generate weekly sales time series from 2000-01-01 to 2020-01-01
set.seed(123)
sales <- ts(rnorm(1040, mean = 100, sd = 50), start = c(2000, 1), frequency = 52)

mydate <- as.Date('2010-06-06')

# Plot the time series with a vertical line at January 1, 2010
    plot.ts(sales, main = "Weekly Sales", xlab = "Date", ylab = "Sales", col = "blue", ylim = c(0, max(sales)*1.1))

abline(v = lubridate::decimal_date(mydate),
       lty = "dotted", lwd = 2, col = "red")

0yycz8jy

0yycz8jy2#

我不知道为什么它没有出现在图上。下面是一个方法,通过将ts转换为 Dataframe 并使用ggplot2方法,

library(ggplot2)

start_year <- start(sales)[1]
start_period <- start(sales)[2]

dates <- seq(as.Date(paste(start_year, 1, 1, sep = "-")) + (start_period - 1) * 7, 
             by = "week", 
             length.out = length(sales))

sales_df <- data.frame(Date = dates, Sales = c(sales))

ggplot(sales_df, aes(x = Date, y = Sales)) +
     geom_line(color = "blue") +
     geom_vline(aes(xintercept = as.Date("2010-01-01")), linetype = "dotted", color = "red", linewidth = 2)

这就给了

相关问题