【发布时间】:2021-03-31 01:24:42
【问题描述】:
我在循环中运行以下每个图都没有问题,但由于某种原因,当我尝试在 grid.arrange 中组合它们时,轴会自动缩放。我不知道如何不自动缩放。我实际上只是想将 ggplots 组合在一起(就像我使用 par(mfrow = c(2,3)) 和 base R)。
我认为 X 轴实际上是重新格式化的日期时间 (as.posixct) 的事实正在抛弃它。理想情况下,我希望 X 轴只显示小时。
library(ggplot2)
library(bp)
df <- data(hypnos_data)
ids <- unique(df$ID)
id_tab <- cbind(ids, c(1:5))
index <- c(8:23, 0:7)
plot_list <- list()
for(i in ids){
subs <- df[which(df$ID == i & df$VISIT == 1),]
subs$DATE.TIME <- as.POSIXct(subs$DATE.TIME)
subs$hour_rec <- lubridate::hour(subs$DATE.TIME)
subs$hour_rec <- factor(subs$hour_rec, levels = as.character(index), ordered = T)
row.names(subs) <- NULL
tmp <- subs %>% dplyr::filter(WAKE == 0)
min(tmp$hour_rec)
p <- ggplot2::ggplot(subs, ggplot2::aes(x = DATE.TIME, y = SYST)) +
geom_rect(aes(xmin = min(tmp$DATE.TIME), xmax = max(tmp$DATE.TIME), ymin = -Inf, ymax = Inf),
fill = "navajowhite2", alpha = 0.03) +
ggplot2::geom_point(aes(y = SYST), col = 'blue') +
ggplot2::geom_smooth(aes(y = SYST), method = "loess", col = 'blue') +
ggplot2::geom_point(aes(y = DIAST), col = 'red') +
ggplot2::geom_smooth(aes(y = DIAST), method = "loess", col = 'red') +
scale_x_datetime(date_label = "%H:%M", date_breaks = "1 hour") +
theme(axis.text.x = element_text(angle=45)) +
ggtitle( paste("BP Profile for Subject: ", i, sep = "") )
plot_list[[match(i, id_tab)]] <- p
print(p)
#grid::grid.newpage()
}
上面的代码应该产生5个类似的图(这是正确的):
个别地块输出
gridExtra::grid.arrange(grobs = plot_list, ncol = 2 )
但是,尝试使用 grid.arrange 组合它们会产生以下结果:
grid.arrange 绘图输出
【问题讨论】:
-
你在哪里看这个?您是否尝试扩大查看器?
-
这是在 RStudio 中。我尝试扩展它,但我无法理解它。
标签: r ggplot2 dplyr lubridate gridextra