2016-03-01 51 views
3

我正在寻找绘制geom_tile的实心轮廓和直接在它下面的相应原始轨迹,两者之间没有空间。当使用gridExtra或cowplot时,我可以将它们关闭,但不能将原始轨迹的顶部放在填充轮廓的x轴上。下面是详细信息:一个图中的两个ggplots,贴在一起

数据

library(reshape2) 
library(ggplot2) 
volcano=volcano 
volcano3d=melt(volcano) 
names(volcano3d) <- c("x", "y", "z") 

地块

fill=ggplot(volcano3d,aes(x,y,z))+geom_tile(aes(fill=z)) 
raw=ggplot(volcano3d,aes(x,y))+geom_line()+theme(aspect.ratio=1/20) 

我尝试

library(gridExtra) 
grid.arrange(fill,raw,heights=c(5,1) 

虽然他们非常接近,我想做几件事:

  1. 将底部轨迹向上移动,以便底部轨迹的顶部触及轮廓图的x轴。
  2. 对齐两轴,使所有0,25,50,75都对齐。在cowplot中,您可以使用对齐参数,这很好,但我无法弄清楚如何将它们彼此靠近。

IDEAL图

这是从不同的数据集,但其布局的一个很好的例子。 enter image description here

想法?

回答

4

这让你接近你正在寻找的东西,除了图例在绘图区域内。我使用theme(plot.margin)来调整绘图周围的顶部和底部间距,并使轴对齐。 expand = 0允许数据扩展到图的边缘(如你的例子)。创建每个图的grobs并将宽度设置为相等允许您在arrangeGrob中控制高度和宽度。

library(reshape2) 
library(ggplot2) 
library(gridExtra) 
library(grid) 
volcano=volcano 
volcano3d=melt(volcano) 
names(volcano3d) <- c("x", "y", "z") 

fill=ggplot(volcano3d,aes(x,y,z))+geom_tile(aes(fill=z)) + 
theme(axis.text.x = element_blank(), 
    legend.position=c(1,1), 
    legend.justification=c(1, 1), 
    axis.title.x = element_blank(),axis.ticks=element_blank(), 
    plot.margin = unit(c(1,1,0,1), "cm")) + 
scale_x_continuous(expand = c(0, 0)) + 
scale_y_continuous(expand = c(0, 0)) 
raw=ggplot(volcano3d,aes(x,y))+geom_line()+ 
theme(aspect.ratio=1/20, 
    plot.margin = unit(c(-1.2,1,1,1), "cm")) + 
scale_x_continuous(expand = c(0, 0)) 

gA <- ggplotGrob(fill) 
gB <- ggplotGrob(raw) 
gA$widths <- gB$widths 
grid.newpage() 
grid.draw(arrangeGrob(gA,gB, heights = c(4/5, 1/5))) 
+0

完美。情节内的传说应该和我的同事一样好,如果不是,他们可以处理它。 –

2

可以将图例保留在图表之外。在两个gtables中,gA有一个额外的列来表示图例。因此,向gB添加一列,其宽度与gA图例相同。

此外,我会从gtables中删除相关的顶部和底部空白行。

library(reshape2) 
library(ggplot2) 
library(gridExtra) 
library(gtable) 
library(grid) 
volcano=volcano 
volcano3d=melt(volcano) 
names(volcano3d) <- c("x", "y", "z") 

fill = ggplot(volcano3d, aes(x, y, z)) + 
    geom_tile(aes(fill=z)) + 
    scale_x_continuous(expand = c(0, 0)) + 
    scale_y_continuous(expand = c(0, 0)) 

raw = ggplot(volcano3d,aes(x,y)) + 
    geom_line() + 
    scale_x_continuous(expand = c(0, 0)) 

gA <- ggplotGrob(fill) 
gB <- ggplotGrob(raw) 

ga = gA[-c(10:7), ] # Remove bottom rows from gA 
gb = gB[-c(1:5), ] # Remove top rows from gB 

# Add extra column to gB gtable 
gb = gtable_add_cols(gb, ga$widths[7:8], 6) 

ga$widths <- gb$widths 
grid.newpage() 
grid.draw(arrangeGrob(ga,gb, heights = c(4/5, 1/5)))