Complexheatmap::pheatmap圖cell尺寸設置

首先放出參考鏈接:

我們在畫熱圖的時候,有時候會遇到想調整熱圖中單元格子的尺寸的情況。并且希望可以動態(tài)的設置,也就是不管是多少數據,格子都可以隨著圖片大小縮放。
Complexheatmap中的Heatmap()函數,有一個width和height參數可以設置

Heatmap(mat, name = "mat", 
    width = ncol(mat)*unit(5, "mm"), 
    height = nrow(mat)*unit(5, "mm"))

而對應到pheatmap中就是cellwidth和cellheight,設置的就是cell的長和寬。

https://jokergoo.github.io/2020/05/06/translate-from-pheatmap-to-complexheatmap/

所以只需要在pheatmap中設置這兩個參數

library("ComplexHeatmap")
test = matrix(rnorm(200), 20, 10)
test[1:10, seq(1, 10, 2)] = test[1:10, seq(1, 10, 2)] + 3
test[11:20, seq(2, 10, 2)] = test[11:20, seq(2, 10, 2)] + 2
test[15:20, seq(2, 10, 2)] = test[15:20, seq(2, 10, 2)] + 4
colnames(test) = paste("Testlong", 1:10, sep = "")
rownames(test) = paste("1230_", 1:20, sep = "")
ht <- pheatmap(test,
        annotation_col = NA, # 列分組
        cellwidth =20, cellheight=20,
        annotation_row =NA,  # 行分組
        annotation_colors = ann_colors,  # 指定樣本分組顏色, list格式
        color = colorRampPalette(c("#0000FF", "#FFFCC8", "#FF0000"))(100), # 熱圖色卡顏色
        border_color = NA,  # cell有無邊框,或指定顏色
        cluster_rows = TRUE,  # 顯示行聚類
        cluster_cols = TRUE,  # 顯示列聚類
        legend = TRUE, #是否顯示色標圖例
        main = "jsd diversity distance", # 圖標題
        display_numbers = FALSE, number_format = "%.1f", number_color="Black", fontsize_number=4,  # cell中是否顯示數值;格式設置
        angle_col = "45",  # options (0, 45, 90, 270 and 315)  # 調整列文字角度
        annotation_legend = TRUE,
        show_rownames = F
)

然后使用draw()得到繪制好的圖,根據ComplexHeatmap:::width(ht)ComplexHeatmap:::height(ht)可以獲取此時圖的長和寬,注意這里包括所有的元素,包括圖例,樹狀圖等,所以如果需要調整參數一定要在計算圖尺寸之前全部設置好!可以直接使用如下函數來獲取尺寸。

calc_ht_size = function(ht, unit = "inch") {
    pdf(NULL)
    ht = draw(ht)
    w = ComplexHeatmap:::width(ht)
    w = convertX(w, unit, valueOnly = TRUE)
    h = ComplexHeatmap:::height(ht)
    h = convertY(h, unit, valueOnly = TRUE)
    dev.off()
    c(w, h)
}

不過要注意的一點是,這里是pdf/svg輸出,所以設置的單位是inch,如果是png,需要設置為pt。
使用方式如下:

size = calc_ht_size(ht)
width = size[1]
height = size[2]
pdf("heatmap.pdf", height = height , width =width)
print(ht)
dev.off()

可以畫出來很正方形的熱圖。


?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容