1

我一直在使用 cowplot 中的 plot_grid 命令来安排我的绘图。我使用标签功能,我的情节在这方面看起来都一样。但是,当我 'hv' 对齐一些 y 轴限制非常不同的图时,例如下面的图,似乎使用了最短 y 范围的图的高度。

来自cowplot hv的平滑图对齐

如果我只是“v”对齐绘图,它在某些方面看起来更好,但很难调整绘图大小并使标签看起来不错。我希望绘图高度不考虑 x 轴标签等,如上所示。

v 对齐图

使用gtables,我可以获得所需的宽度/高度(如下),但这让我在文档中的所有图形中没有一致的标签。我可以使用与 cowplot 的“hv”对齐并指定要使用的绘图高度吗?

剧情不错,没有标签

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

1 回答 1

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)

在此处输入图像描述

于 2016-03-05T02:10:54.847 回答