我在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")
我看不见线-我试着改变厚度,但我还是看不见。
有人能告诉我如何正确地做吗?
谢谢!
2条答案
按热度按时间5n0oy7gb1#
这条线没有出现在图上的原因是
plot.ts()
使用公元前的整年作为时间单位,而as.numeric(as.Date())
的输出是以Unix time为单位(即从00:00:00 UTC 1970-01-01开始的秒):你的问题的解决方案是对初始图和
abline()
使用相同的时间单位。这就是ggplot中建议解决方案的另一个答案。如果你宁愿坚持以R为基数,@tpetzoldt的评论有一个简单的方法来获得你想要的:适用于2010-01-01。如果您需要更精细的时间分辨率,请首先计算一年中的第几天,除以365并将其用作小数。
lubridate
使其非常简单:或者更好:使用
lubridate::decimal_date()
。完整答案:
0yycz8jy2#
我不知道为什么它没有出现在图上。下面是一个方法,通过将
ts
转换为 Dataframe 并使用ggplot2
方法,这就给了