Reputation: 438
I am using Prophet package to forecasting in groups in a dataframe, and I want to create plots using the grouped dataframe.
I was following the answers in Using Prophet Package to Predict by Group in Dataframe in R. Are there easier ways to create the plots, compared to how I did it below?
library(dplyr)
library(prophet)
df <- data_frame(ds = seq(as.Date("2017/01/01"), as.Date("2019/01/01"), "month"),
a = rnorm(n = 25, mean = 100000, sd = 7500),
b = rnorm(n = 25, mean = 100000, sd = 7500),
c = rnorm(n = 25, mean = 100000, sd = 7500))
The columns a, b and c are sales numbers for each product. And, I would like to run forecasting for all 3 products and the total sales in next 12 periods.
So, I tidy up the dataframe, then do group forecasting.
d1 <- df %>%
gather(key = "prod", value = "y", a:c) %>%
nest(-prod) %>%
mutate(m = map(data, prophet)) %>%
mutate(future = map(m, make_future_dataframe, period = 12, freq = "month")) %>%
mutate(forecast = map2(m, future, predict)) %>%
mutate(p = map2(m, forecast, plot))
The output looks like this:
# A tibble: 3 x 6
dept data m future forecast p
<chr> <list> <list> <list> <list> <list>
1 a <tibble [25 x 2]> <S3: prophet> <data.frame [37 x 1]> <data.frame [37 x 16]> <S3: gg>
2 b <tibble [25 x 2]> <S3: prophet> <data.frame [37 x 1]> <data.frame [37 x 16]> <S3: gg>
3 c <tibble [25 x 2]> <S3: prophet> <data.frame [37 x 1]> <data.frame [37 x 16]> <S3: gg>
Then, I create the plots manually, and rearrange them using grid.arrange
gridExtra::grid.arrange(d1$p[[1]], d1$p[[2]], d1$p[[3]]
Are there any ways to do it quicker and automatically?
Upvotes: 0
Views: 900
Reputation: 555
Single plot: Using cowplot
cowplot::plot_grid(plotlist =d1$p)
Multiple plots: Using purrr::walk function:
walk(.x=d1$p,.f=gridExtra::grid.arrange)
.x is the first parameter and .f is the function. If you need more than one parameter then you should use walk2 (2) or pwalk (3+)
Upvotes: 0
Reputation: 8364
I couldn't find a way to pipe the call to grid.arrange
, but you can use do.call
to avoid manually selecting plots.
do.call(gridExtra::grid.arrange, d1$p)
Example:
library(dplyr)
library(prophet)
library(tidyr)
library(purrr)
df <- data_frame(ds = seq(as.Date("2017/01/01"), as.Date("2019/01/01"), "month"),
a = rnorm(n = 25, mean = 100000, sd = 7500),
b = rnorm(n = 25, mean = 100000, sd = 7500),
c = rnorm(n = 25, mean = 100000, sd = 7500))
d1 <- df %>%
gather(key = "prod", value = "y", a:c) %>%
nest(-prod) %>%
mutate(m = map(data, prophet)) %>%
mutate(future = map(m, make_future_dataframe, period = 12, freq = "month")) %>%
mutate(forecast = map2(m, future, predict)) %>%
mutate(p = map2(m, forecast, plot))
Upvotes: 3