简体   繁体   中英

R - Adjust graph axis with cowplot

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?

Try with patchwork :

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

Output:

在此处输入图像描述

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