Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

ggplot2 - 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?

question from:https://stackoverflow.com/questions/65849942/r-adjust-graph-axis-with-cowplot

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try with patchwork:

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

Output:

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...