我已经看到很多解决方案来对齐ggplot2图的绘图区域。但是,我有一些由输出来自arrangeGrob的结果的函数创建的图。我想将它们绘制在一列中,x轴的起点和终点都对齐。这是一个可运行的例子。
运行示例,
library(ggplot2)
library(gridExtra)
topPlot <- f(TRUE, TRUE, TRUE, "Dataset 1")
bottomPlot <- f(FALSE, FALSE, FALSE, "Dataset 2")
grid.draw(arrangeGrob(topPlot, bottomPlot, nrow = 2))
f的定义:
f <- function(x,y, z, t)
{
showLegends = x
knownClasses <- rep(c("Healthy", "Sick"), each = 5)
plotData <- data.frame(name = LETTERS[1:10],
type = rep(c("Method 1", "Method 2"), each = 10),
class = rep(c("Healthy", "Sick"), each = 5),
Error = runif(20))
classesPlot <- ggplot(data.frame(Class = knownClasses), aes(1:length(knownClasses), factor(1)), environment = environment()) +
geom_tile(aes(fill = Class, height = 10)) +
scale_x_discrete(expand = c(0, 0), breaks = NULL, limits = c(1, length(knownClasses))) +
scale_y_discrete(expand = c(0, 0), breaks = NULL) +
labs(x = '', y = '')+ theme(legend.position = ifelse(showLegends, "right", "none"))
errorPlot <- ggplot(plotData, aes(name, type)) + geom_tile(aes(fill = Error)) + theme_bw() +
theme(legend.position = ifelse(showLegends, "right", "none"),
axis.text.y = if(y) element_text(size = 8) else element_blank()) + ylab(if(z) "Label" else NULL)
classGrob <- ggplot_gtable(ggplot_build(classesPlot))
errorGrob <- ggplot_gtable(ggplot_build(errorPlot))
commonWidth <- unit.pmax(classGrob[["widths"]], errorGrob[["widths"]])
classGrob[["widths"]] <- commonWidth
errorGrob[["widths"]] <- commonWidth
arrangeGrob(classGrob, errorGrob, nrow = 2, heights = c(1, 3), main = t)
}
在实际情况中,两个数据集将在不同比例的类中具有不同的样本,因此除非在ggplot2中允许每个绘图的多个颜色标度,否则不能选择除去每个错误图上方的类颜色标度。 / p>
如何修改此代码以对齐绘图区域?