简体   繁体   English

R - 使用牛图调整图形轴

[英]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).我想 plot 使用 ggplot 进行时间序列分析的一些结果,将变量及其预测绘制在同一张图上,同时将错误绘制在下图中(类似于plot.ts 的工作方式,但我不能使用这个库)。

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 :尝试patchwork

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

Output: Output:

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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