gpt4 book ai didi

r - 使用多图设置图之间的边距

转载 作者:行者123 更新时间:2023-12-02 06:31:38 26 4
gpt4 key购买 nike

为了显示多个图,我使用了 multiplot ( http://www.cookbook-r.com/Graphs/Multiple_graphs_on_one_page_(ggplot2)/ ),现在我有两个图共享相同的 x 轴范围并在彼此上方绘制:

multiplot(plot1, plot2)

我使用以下方法删除了 x 轴标签和标题:

xlab(NULL) + theme(axis.text.x=element_blank(),axis.ticks.x=element_blank())

但是两个图之间仍然有一个白边。我怎样才能使这个边距变小或删除它?

最佳答案

要减少图之间的空间,请删除顶部图的底部边距并删除底部图的顶部边距。下面的代码将这些边距设置为 0,这仍然会导致图之间有一点空白。您可以使这些边距略微为负(可能是 -0.1 左右)以完全删除空白。我们使用 gridExtra 包中的 grid.arrange 来布置绘图,而不是 multiplot 函数。 :

library(grid)
library(gridExtra)

## Create two sample plots with the same x axis using built-in mtcars data frame

# Top plot: Remove bottom margin, x-labels, and x title
p1 = ggplot(mtcars, aes(wt, mpg)) + geom_point() +
xlab(NULL) +
theme(axis.text.x=element_blank(),axis.ticks.x=element_blank(),
plot.margin=unit(c(1,1,0,1), "lines"))

# Bottom plot: Remove top margin
p2 = ggplot(mtcars, aes(wt, carb)) + geom_point() +
theme(plot.margin=unit(c(0,1,1,1), "lines"))

# Lay out plots in one column
grid.arrange(p1, p2, ncol=1)

enter image description here

上述布局有两个问题:(1) y 轴没有正确对齐,(2) 下部绘图区域的高度小于上部绘图区域的高度。下面的代码解决了这些问题:

# Left justify plots
# Source: http://stackoverflow.com/a/13295880/496488
gA <- ggplotGrob(p1)
gB <- ggplotGrob(p2)

maxWidth = grid::unit.pmax(gA$widths[2:5], gB$widths[2:5])
gA$widths[2:5] <- as.list(maxWidth)
gB$widths[2:5] <- as.list(maxWidth)

# Lay out justified plots. Use heights argument to equalize heights of each plot area
grid.arrange(gA, gB, heights=c(0.47,0.53), ncol=1)

enter image description here

您可以使用与左对齐绘图相同的技巧来精确均衡每个绘图区域的高度(而不是使用 grid.xml 的 heights 参数通过肉眼来实现。安排),但随后情节边距被添加回来。我不确定如何处理,但这里有代码供引用:

maxHeight = grid::unit.pmax(gA$heights[2:5], gB$heights[2:5])
gA$heights[2:5] <- as.list(maxHeight)
gB$heights[2:5] <- as.list(maxHeight)

关于r - 使用多图设置图之间的边距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34496648/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com