首页 > 解决方案 > 带有 facet_wrap 的 cowplot::plot_grid - y 轴标题与轴标签重叠

问题描述

我只在短时间内使用 R 和 gglot,所以我非常感谢任何帮助!由于我喜欢使用辅助 y 轴来显示我的平均值,因此 facet_wrap 仅适用于并排显示三个图。所以我使用库“cowplot”来管理它。

3 与cowplot 并排的地块

为了保持灰色标题字段 - 就像在其他图表中一样 - 毕竟我将 facet_wrap 应用于单个图表。但是 y 轴标签在 y 刻度标签上移动。无论是通过边距,还是边框或其他方式,我都设法将 y 轴标签推到外面。

这是一个示例代码:

set.seed(42)  ## for sake of reproducibility
n <- 6
dat_A <- data.frame(id=1:n, 
                  date=seq.Date(as.Date("2020-12-26"), as.Date("2020-12-31"), "day"),
                  group=rep(LETTERS[1:1], n/2),
                  age=sample(18:30, n, replace=TRUE),
                  type=factor(paste("type", 1:n)),
                  x=rnorm(n))

dat_B <- data.frame(id=1:n, 
                    date=seq.Date(as.Date("2020-12-26"), as.Date("2020-12-31"), "day"),
                    group=rep(LETTERS[2:2], n/2),
                    age=sample(18:30, n, replace=TRUE),
                    type=factor(paste("type", 1:n)),
                    x=rnorm(n))

p1 <- ggplot(dat_A, aes(x=x, y=age, fill=group))+
  geom_boxplot()+
  geom_hline(aes(yintercept = age), linetype = "dashed")+
  geom_jitter(alpha = .4)+
  facet_wrap(~group, scales = "free")+
  scale_y_continuous(limits = c(10, 30), expand = expansion(mult = c(.05, .05)), sec.axis = sec_axis(~ ., labels = scales::number_format(accuracy = 0.1), breaks = dat_A$age))+
  
  guides(fill=FALSE)+
  theme_bw(base_size = 9)+

labs(
  y = expression(~bold(age)~'in a'),
  color = NULL)+
theme(
  text = element_text(family="Arial", size=9),
  plot.margin = unit(c(0,.7,0,0), "cm"), # c(top, right, bottom, left)
  axis.title.x = element_blank(),
  legend.position = "none"
  )

p2 <- ggplot()+
  geom_point(aes(x, age), dat_B)+
  facet_wrap(~group, scales = "free")+
  labs(
    y = expression(~bold(age)~'in a'),
    color = NULL)+
  theme(
    plot.margin = unit(c(0,.7,0,0), "cm"), # c(top, right, bottom, left)
    axis.line.x = element_blank()
  )

library(cowplot)
plot_grid(p1, p2, p1, align = "h", nrow = 1, ncol = 3, rel_widths = c(22/100, 39/100, 39/100),
          labels = c("A", "B", "C"),
          label_size = 9,
          label_fontfamily = "Cambria", ## emf seems to overwrite "fontfamily"
          label_fontface = "bold",
          label_colour = NULL,
          label_x = -0.03,
          label_y = 1 #0.05
)

也许对某些人来说很有趣,否则可以删除该问题。对我来说已经解决了。

谢谢马耳他

标签: rggplot2facet-wrap

解决方案


推荐阅读