使用多重时间

时间:2015-12-28 15:56:25

标签: r ggplot2

为了显示多个图,我使用多重图(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())

但两个地块之间仍然存在白色边缘。如何缩小或删除此边距?

3 个答案:

答案 0 :(得分:5)

要减少绘图之间的间距,请删除顶部绘图的下边距并删除底部绘图的上边距。下面的代码将这些边距设置为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) 

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

您可以使用与我们用于左对齐绘图相同的技巧来完全均衡每个绘图区域的高度(而不是使用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) }进行,但是然后将情节边缘加回。我不确定如何处理,但这里有参考代码:

FS...

答案 1 :(得分:2)

ggplot2的最后一次更新可以更好地控制情节。例如见:

ggplot(mtcars, aes(disp, mpg)) +
     geom_point() +
     facet_wrap(~vs)

您可以进一步调整标签,行数以及比例的显示方式,例如:nrow = 2; scales = "free"

enter image description here

答案 2 :(得分:2)

比您想象的更容易重新排列数据,以便您可以利用ggplot2中已存在的良好对齐功能。请参阅下面的示例复制eipi10的答案,但无需使用ggplotGrob。

您需要做的只是选择要绘制的列以及ID列(在本例中为汽车模型和x轴值列)。然后融化,并准备使用标准的facet程序进行绘图。

请注意,facet_grid调用中的“切换”选项是一项新功能,您可以通过更新到最新的CRAN版本来访问该功能。我用它来替换常规的y轴标题,使用theme省略了该标题。

关于这种方法的好处是,这些图总是完全对齐。

library("ggplot2")
library("dplyr")
library("reshape2")

df <- mtcars %>% 
  add_rownames(var = "Model") %>%
  select(Model, wt, mpg, carb) %>%
  melt(id.vars = c("Model","wt"))

ggplot(df)+
  aes(x=wt, y=value)+
  geom_point()+
  theme(strip.background=element_blank())+
  facet_grid(variable ~ ., scales="free_y", switch="y")

enter image description here

相关问题