为了显示多个图,我使用多色图(http://www.cookbook-r.com/Graphs/Multiple_graphs_on_one_page_(ggplot2)/),现在我有两个共享相同x轴范围并绘制在彼此上方的图:
multiplot(plot1, plot2)
Run Code Online (Sandbox Code Playgroud)
我使用以下方法删除了x轴标签和标题:
xlab(NULL) + theme(axis.text.x=element_blank(),axis.ticks.x=element_blank())
Run Code Online (Sandbox Code Playgroud)
但两个地块之间仍有一个白色边缘.如何缩小或删除此边距?
要减少绘图之间的间距,请删除顶部绘图的下边距并删除底部绘图的上边距.下面的代码将这些边距设置为0,这仍然会在图之间产生一点点空白.您可以使这些边距略微为负(可能为-0.1左右)以完全删除空白区域.而不是multiplot功能,我们使用grid.arrange从gridExtra包铺陈情节.:
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)
Run Code Online (Sandbox Code Playgroud)
上述布局存在两个问题:(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)
Run Code Online (Sandbox Code Playgroud)
您可以使用与我们用于左对齐图形相同的技巧来完全均衡每个绘图区域的高度(而不是使用heights参数来通过眼睛进行grid.arrange),但随后将绘图边距添加回来.我不知道如何处理,但这里的代码供参考:
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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2743 次 |
| 最近记录: |