使用'hv'对齐在plot_grid中指定绘图高度:cowplot

时间:2016-03-04 23:53:00

标签: r ggplot2 gtable cowplot

我一直在使用牛皮图中的plot_grid命令来安排我的情节。我使用标签功能,我的情节在这方面看起来都一样。但是,当我'对齐一些具有非常不同的y轴限制的图时,例如下面的那个图时,会出现使用y的最短范围的图的高度。

smooshed plot from cowplot hv aligned

如果我只是'v'对齐情节,它在某些方面看起来会更好,但很难调整情节并使标签看起来很好。我更喜欢绘图高度不考虑x轴标签等,如上所述。

v aligned plot

使用gtables,我可以获得所需的宽度/高度(下图),但是这些文件中的所有图形都没有一致的标签。我可以在牛皮图中使用'hv'对齐并指定要使用的绘图高度吗?

nice plot, no labels

library(ggplot2)
library(dplyr)
library(scales)
library(grid)
library(cowplot)

data(iris)

iris <- iris %>% mutate(Petal.Width2 = ifelse(Species == "setosa", Petal.Width * 75, Petal.Width))

p1 <- ggplot(data=iris, aes(x = factor(Species), y=Sepal.Width)) + 
  geom_bar(stat="identity") +
  labs(x = NULL, y = "Plot One") +
  scale_y_continuous(labels = percent) +
  theme(axis.text.x = element_blank(), 
        axis.title.y = element_text(vjust=1), plot.margin=unit(c(2,2,0,2),"mm"))

p2 <- ggplot(data=iris, aes(x = factor(Species), y=Petal.Width2)) + geom_bar(stat="identity") +
  labs(x = NULL, y = "Plot Two") +
  scale_y_continuous(labels = percent) +
  theme(axis.text.x = element_blank(), 
        axis.title.y = element_text(vjust=1), plot.margin=unit(c(0,2,0,2),"mm"))
p3 <- ggplot(data=iris, aes(x = factor(Species), y=Petal.Length*0+.01)) + geom_bar(stat="identity") +
  labs(x = "SPECIES", y = "The Third plot") +
  scale_y_continuous(labels = percent) +
  theme( axis.title.y = element_text(vjust=1, color="blue"), plot.margin=unit(c(0,2,0,2),"mm"),
         axis.text.x = element_text(angle = 90, hjust=1, vjust=1,face ="italic", size=10))

plot_grid(p1,p2,p3,ncol=1, align="v", labels=c("A", "B", "C"))

# https://stackoverflow.com/a/27408589/1670053
plots <- list(p1, p2, p3)
grobs = lapply(plots, ggplotGrob)
g = do.call(rbind, c(grobs, size="first"))

g$widths = do.call(unit.pmax, lapply(grobs, "[[", "widths"))
grid.newpage()
grid.draw(g)

1 个答案:

答案 0 :(得分:4)

添加标签很容易,

plots <- list(p1, p2, p3)
grobs = lapply(plots, ggplotGrob)
library(gridExtra)
g = do.call(rbind, grobs) #  uses gridExtra::rbind.gtable
panels <- g$layout[g$layout$name=="panel",]

g <- gtable::gtable_add_grob(g, lapply(LETTERS[1:nrow(panels)],
                                       textGrob, vjust=1, y=1, 
                                       gp=gpar(fontface=2)), 
                             t=panels$t, l=2)

grid.newpage()
grid.draw(g)

enter image description here