2013-02-27 175 views
4

我試圖在相同的png或pdf中並排顯示兩個或多個熱圖。佈局或mfcol不起作用的情況下。有人能幫我解決這個問題嗎?要在同一個PDF中並排顯示兩張熱圖R

+1

面值( mfrow = c(2,1)) x < - as.matrix(mtcars) heatmap.2(x) heatmap.2(x)這應該在同一個設備中創建兩個熱圖,但不是這樣。 – 2013-02-28 08:51:58

回答

3

至於heatmap.2的幫助文件中所述,

「heatmap.2()」用途「佈局」,並繪製在一個2x2佈局的下 右下角的「形象」。因此,它可以在多列/行佈局中使用,即當'par(mfrow = *)'或 '(mfcol = *)'被調用時,它可以是而不是是 。

熱圖的情況也是如此。

0

這是一種做法。這是非常黑客,但我認爲,當一個功能沒有做你想做的事情時,最好的解決辦法就是讓它做到這一點。
功能heatmap.2包含中途以下三行通過它的代碼:

... 
op <- par(no.readonly = TRUE) 
on.exit(par(op)) 
layout(lmat, widths = lwid, heights = lhei, respect = FALSE) 
... 

正是因爲有了他們,既然覆蓋它,你不能使用layoutpar(mar=...)。 heatmap.2的代碼複製到一個新的功能(比如heatmap.3),並刪除這些三條線:

heatmap.3 <- function(... #etc etc with the exact same code minus those 3 lines 

然後你的代碼產生你的兩個熱圖並排會,例如:

layout(rbind(c(4,3,8,7),c(2,1,6,5)), 
     widths = c(1,2,1,2), heights = c(1,2), respect = FALSE) 
heatmap.3(x) 
heatmap.3(y) 

在準備佈局時,請記住熱圖代碼首先繪製熱圖本身,然後繪製「行」樹形圖,然後繪製「col」樹形圖,最後繪製直方圖,因此從上到下,從左到右的順序是4, 3,2,1表示當兩個熱圖並排時,它變爲4,3,8,7,2,1,6,5。

1

具有完全相同的問題後,我想出了以下解決方案:

1)使用GGPLOT2使用樹形圖的熱圖喜歡這裏:Reproducing lattice dendrogram graph with ggplot2,然後用的multiplot安排()函數(http://www.cookbook-r.com/Graphs/Multiple_graphs_on_one_page_%28ggplot2%29/

2)但是,這是很多工作,我想堅持使用基本的heatmap()函數。以下是簡單的(雖然不是純R),如果你有安裝ImageMagick的Linux上工作:

m <- matrix(runif(10^2), ncol=10) 
for (i1 in 1:4) { 
    ifile <- paste0(i1,'_heatmap.pdf') 
    pdf(ifile) 
    heatmap(m) 
    d <- dev.off() 
} 
system('montage -geometry 100% -tile 2x2 ./*_heatmap.pdf outfile.pdf') 
2

下面是使用最近推出的gridGraphics包一個選項,

enter image description here

library(gridGraphics) 
library(grid) 
heatmap(as.matrix(mtcars)) 

library(gridGraphics) 
grab_grob <- function(){ 
    grid.echo() 
    grid.grab() 
} 

g <- grab_grob() 
grid.newpage() 

# library(gridExtra) 
# grid.arrange(g,g, ncol=2, clip=TRUE) 

lay <- grid.layout(nrow = 1, ncol=2) 
pushViewport(viewport(layout = lay)) 
grid.draw(editGrob(g, vp=viewport(layout.pos.row = 1, 
            layout.pos.col = 1, clip=TRUE))) 
grid.draw(editGrob(g, vp=viewport(layout.pos.row = 1, 
            layout.pos.col = 2, clip=TRUE))) 
upViewport(1) 
+0

只是一個更新:這個函數也適用於'heatmap.2'。從上面的代碼改編而來,我只是加載'庫(gplots)'並將'heatmap(as.matrix(mtcars))'改爲'heatmap.2(as.matrix(mtcars))''。 – 2016-12-02 01:16:35

相關問題