简体   繁体   中英

Multiple time-series with face_wrap

I am working on a time-series project. I would like to compare the "y" data to the "y_hat". What I call "y" is the data from my dataset and "y_hat" is what my algorithms have predicted.

I have tried using facet_wrap, unfortunately it plots one time-series by category as you can see on the image :

在此处输入图片说明

nb_of_algorithm <- 6
gather_df <- df_all %>% gather(key="Algorithm", "values", 2:nb_of_algorithm)

ggplot(gather_df, aes(x = ds, y = values)) +
        geom_line(aes(color = Algorithm)) +
        scale_color_brewer(palette="Dark2") +
        facet_wrap(~ Algorithm)

And I add a sample of what my dataframe looks like

            ds     Algorithm    values
1   2018-10-19             y  8115.000
2   2018-10-20             y  8730.000
3   2018-10-21             y  7155.000
4   2018-10-22             y   570.000
164 2018-10-19 y_hat_xgboost  3458.394
165 2018-10-20 y_hat_xgboost  6424.176
166 2018-10-21 y_hat_xgboost  3416.893
167 2018-10-22 y_hat_xgboost 12041.853
168 2018-10-23 y_hat_xgboost  9801.245
169 2018-10-24 y_hat_xgboost 11081.888
327 2018-10-19  y_hat_nnetar  7188.586
328 2018-10-20  y_hat_nnetar  6606.201
329 2018-10-21  y_hat_nnetar 10488.071
330 2018-10-22  y_hat_nnetar 17417.546
331 2018-10-23  y_hat_nnetar 14230.000

The expected results would be the same graph as above, with on the same plot:
* "y" and "y_hat_xgboost"
* "y" and "y_hat_nnetar"
* and so on ...

So I can compare them to the real data

Thanks for your help

Essentially we want two things: 1) not to have a separate category for y , 2) to add an extra layer of y in each of the remaining categories. Hence, with

ggplot(gather_df %>% filter(Algorithm != "y"), aes(x = ds, y = values)) +
  geom_line(aes(color = Algorithm)) +
  scale_color_brewer(palette = "Dark2") +
  facet_wrap(~ Algorithm) + 
  geom_line(data = gather_df %>% filter(Algorithm == "y") %>% select(-Algorithm))

we achieve that, where gather_df %>% filter(Algorithm != "y") does part 1) and the last line does 2).

If you wish the curve of y to appear in the legend, you may also add, say, aes(color = "y") to the last line. This gives

在此处输入图片说明

If you want "y" on every panel you don't want to gather it. Try this:

nb_of_algorithm <- 6
gather_df <- df_all %>% 
    gather(key="Algorithm", "values", 2:nb_of_algorithm, -y)

ggplot(gather_df, aes(x = ds, y = values)) +
    geom_line(aes(color = Algorithm)) +
    geom_line(aes(y = y), colour = "black") +
    scale_color_brewer(palette="Dark2") +
    facet_wrap(~ Algorithm)

I don't have the data so I could't try it out, but I hope it at least gets you in the right direction.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM