cowplot:对齐两个图时,轴标题强制对齐

时间:2018-09-21 20:37:34

标签: r ggplot2 cowplot

此代码复制了问题:

library(ggplot2)

set.seed(0)
df <- data.frame(ID = letters[1:10],
                 Var = rnorm(10),
                 "Some_very_long_label_names" = rnorm(10),
                 "Not_so_long" = rnorm(10),
                 "Short" = rnorm(10),
                 "Incredibly_long_label_name_why_oh_why" = rnorm(10),
                 "Etc" = rnorm(10))
melted_df <- reshape2::melt(df)

p1 <- ggplot(df, aes(ID, Var)) +
    geom_bar(stat = "identity") +
    theme(axis.title.x = element_blank())

p2 <- ggplot(melted_df, aes(ID, variable)) +
    geom_tile(aes(fill = value)) +
    guides(fill = FALSE)

cowplot::plot_grid(p1, p2, nrow = 2, align = "v", axis = "n")

如果运行该代码,它将生成以下图:

Problematic plot

此图的问题在于第一个图的y轴标题的位置。我以为设置axis = "n"可能会阻止它与第二个图的轴对齐,但是没有。

我想要的输出是该图,该图已对齐图形,但未对齐轴标签。

Desired output

1 个答案:

答案 0 :(得分:1)

您可以改用egg

library(ggplot2)

p1 <- ggplot(df, aes(ID, Var)) +
  geom_bar(stat = "identity") +
  scale_x_discrete(expand = c(0, 0)) +
  theme_bw() +
  theme(axis.title.x = element_blank())

p2 <- ggplot(melted_df, aes(ID, variable)) +
  geom_tile(aes(fill = value)) +
  scale_x_discrete(expand = c(0, 0)) +
  theme_bw() +
  guides(fill = FALSE)

library(egg)
#> Loading required package: gridExtra
ggarrange(p1, p2, nrow = 2)

reprex package(v0.2.1.9000)于2018-09-21创建