我有 tsibble
格式的数据,并标记为 tsdb
:
A tsibble: 15,000 x 6 [1M]
# Key: Industry [60]
# Groups: Industry [60]
Industry Period Sales inventory Purchase Sales.diff
<chr> <mth> <dbl> <dbl> <dbl> <dbl>
1 Apparel manufacturing 2000 Feb 5321 12215 5228 NA
我需要按行业分组绘图,因此我为一个行业编写了以下代码:
tsdb %>%
filter(Industry == "Manufacturing industries") %>%
pivot_longer(c(Sales, inventory, Purchase), names_to = "Series", values_to = "Million_Dollars") %>%
ggplot(aes(x = Period, y = Million_Dollars, color = Series)) +
geom_line() +
facet_grid(vars(Series), scales = "free_y") +
ggtitle("Manufacturing industries") +
theme(plot.title = element_text(hjust = 0.5))
我想在所有三个图表中的选定点“2005 年 5 月”和“2008 年 6 月”处添加垂直线。为此,我尝试添加:
geom_vline(xintercept = yearmonth("2005 May"), linetype = 4) +
我收到此错误
Error in UseMethod("rescale") :
no applicable method for 'rescale' applied to an object of class "c('yearmonth', 'vctrs_vctr')"
我什至尝试过:
geom_vline(xintercept = yearmonth(424), linetype = 4) +
geom_vline(xintercept = scale_x_yearmonth(424), linetype = 4) +
geom_vline(xintercept = scale_x_yearmonth("2005 May"), linetype = 4) +
我在这里得到的错误是:
Error in xj[i] : object of type 'environment' is not subsettable
我猜 yearmonth
需要缩放才能让 ggplot
理解,但我不知道如何做到这一点。我试图获得一条垂直线,然后希望我可以使用 c() 并获得我需要的所有垂直线。我的目标是通过指定时间段来获取垂直线,例如“2005 年 5 月”。
最佳答案
获得您想要的结果的一种方法是从您的期间变量创建一个日期变量。期间仅列出年份和月份,因此您需要在年份和月份中添加人工的月份日期(例如 1)来获取日期。 像这样的事情:
tsdb<span class="math-container">$Date <- paste(tsdb$</span>Period, "1")
此日期变量是字符变量,但您可以使用 lubridate 包中的 ymd() 函数将其转换为日期变量:
tsdb<span class="math-container">$Date <- lubridate::ymd(tsdb$</span>Date)
现在,您可以通过在 ggplot 中将 x = 周期替换为 x = 日期来重新创建绘图。要添加垂直线,只需将此图层添加到 ggplot 中即可:
geom_vline(xintercept = lubridate::ymd("2005 May 1"), linetype = 4)
关于r - 使用时间序列数据在 ggplot 中创建垂直线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66401163/