cowplot: axis title forcefully aligned when aligning two plots

自古美人都是妖i 提交于 2019-12-14 04:04:40

问题


This code replicates the problem:

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")

If you run that code, it'll yield this plot:

The problem with this plot lies in the positioning of the y-axis title of the first plot. I thought perhaps setting axis = "n" would stop it from aligning to the axis from the second plot, but it didn't.

My desired output would be this plot, which has aligned the graphics but not the axis labels.


回答1:


You can use the egg package instead

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)

Created on 2018-09-21 by the reprex package (v0.2.1.9000)



来源:https://stackoverflow.com/questions/52450790/cowplot-axis-title-forcefully-aligned-when-aligning-two-plots

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!