0

I want to plot some results of a time-series analysis with ggplot, plotting the variable and its predictions on the same graph, while having the error plotted on a graph below (similar to how plot.ts work, but I cannot use this library).

Here's my code :

library(ggplot2)
library(cowplot)

set.seed(1111)

my_df = data.frame(
  date = 1:150,
  initial = c(runif(100, max=100), rep(NA, 50)),
  predicted_intra = c(rep(50, 100), rep(NA, 50)),
  predicted_extra = c(rep(NA, 100), 51:100),
  err_intra = c(runif(100, max=100), rep(NA, 50))
)

my_colors = c("Init" = "grey30", "Predict" = "red")

p1 <- ggplot(my_df) + aes(x = date, y = predicted_intra, color="Predict") +
  geom_line() +
  geom_line(aes(y = predicted_extra, color="Predict")) +
  geom_line(aes(y = initial, color="Init")) +
  scale_color_manual(name = "", values = my_colors) + 
  ylab("Numberz")

p2 <- ggplot(my_df) +
  aes(x = date, y = err_intra) + geom_line(color="red") + 
  ylab("Error")

plot_grid(p1, p2, nrow=2, rel_heights = c(2,1))

Which gives : The result of the code above

All is well until the legend shows. Is there a way to align the "date" axis of the two graphs?

Flunec
  • 17
  • 5

1 Answers1

0

Try with patchwork:

library(patchwork)
#Code
G <- p1/p2

Output:

enter image description here

Duck
  • 39,058
  • 13
  • 42
  • 84
  • This is almost what I want, but can you reduce the height of one graph with it? – Flunec Jan 22 '21 at 17:37
  • @Flunec Yeah you can adjust that with `theme()` in the first or second plot and then use `patchwork`. – Duck Jan 22 '21 at 17:40
  • @Flunec You can check this https://stackoverflow.com/questions/53285493/explicitly-set-panel-size-not-just-plot-size-in-ggplot2 for size adjustment! – Duck Jan 22 '21 at 17:49
  • 1
    egg package is interesting, but the alignment break with it. But you answered my initial question, so it's fine anyway. – Flunec Jan 22 '21 at 18:40
  • ok, while searching the patchwork website, I found what I wanted : `plot_layout(heights = c(2, 1))` – Flunec Jan 22 '21 at 19:21
  • @Flunec That is fantastic! Great job! As you can see `patchwork` has options more friendly for users ! Nice! – Duck Jan 22 '21 at 19:22