导读:
R语言处理图片打开一扇新的大门。
rasterImage合并两张PNG图片
一、制作两张PNG图片
png("拼.png")
plot(NULL, xaxt="n", yaxt="n", ylab="", xlab="", xlim=0:1, ylim=0:1)
legend("center", legend=c("拼"), pch=15, pt.cex=5, cex=5, bty='n', col="blue")
dev.off()
png("图.png")
plot(NULL, xaxt="n", yaxt="n", ylab="", xlab="", xlim=0:1, ylim=0:1)
legend("center", legend=c("图"), pch=15, pt.cex=5, cex=5, bty='n', col="red")
dev.off()
打开拼.png和图.png
二、合并拼图
library("png")
img=list()
img[[1]]=readPNG("拼.png")
img[[2]]=readPNG("图.png")
pdf("拼图.pdf", height=14, width=7)
opar=par(no.readonly=TRUE)
par(mfrow=c(2, 1)) # 填充:2行,1列
par(mar=rep(0, 4)) # 去掉边空
for(i in 1:length(img))
{
plot(NA, xlim=0:1, ylim=0:1, xlab="", ylab="", xaxt="n", yaxt="n", bty="n")
rasterImage(img[[i]], 0, 0, 1, 1)
}
par(opar)
dev.off()
打开拼图.pdf
以上方法无法拼接ggplot图
patchwork拼接ggplot图
|: 横排
/: 竖排
install.packages('patchwork')
library(patchwork)
result =
(p1_1/p2_1/p3_1)|(p1_2/p2_2/p3_2)|(p1_3/p2_3/p3_3)|(p1_4/p2_4/p3_4)|(p1_5/p2_5/p3_5)
ggsave(result, file="merge_1.pdf", width=35, height=21)
result_2 =
(p1_1|p2_1|p3_1)/(p1_2|p2_2|p3_2)/(p1_3|p2_3|p3_3)/(p1_4|p2_4|p3_4)/(p1_5|p2_5|p3_5)
ggsave(result_2, file="merge_2.pdf", width=21, height=35)
cowplot拼接pheatmap图,ggsave指定保存
## p1
p1 = pheatmap(df,
cellwidth = 4, fontsize_col = 4,
color = colorRampPalette(c("snow", "deepskyblue3", "black"))(27),
cellheight = 0.15,
show_rownames=F,
cluster_col = F,
annotation_col = group,
annotation_color = list(CAZyme = colors))
p2 = pheatmap(df,
cellwidth = 1.2, fontsize_col = 0.9,
color = colorRampPalette(c("snow", "deepskyblue3", "black"))(27),
cellheight = 0.05,
show_rownames=F,
cluster_col = F, cluster_row = F,
annotation_col = group_cazyme,
annotation_row = group_strain,
annotation_color = list(Module = colors, Region = colors2))
## p1 + p2
res = cowplot::plot_grid(p1$gtable, p2$gtable,
ncol= 1, nrow = 2, labels=c("a","b"))
#draw_plot_label(c("a","b"),c(0,1),c(0,0.5),size = 14)
ggsave(res, file="test3.pdf", units = "mm", width=180, height=200)
###########
## test ##
library(pheatmap)
library(cowplot)
library(ggplot2)
test <- matrix(rnorm(200), 20, 10)
mfs <- mfs_ma <- mfs_fe <- pheatmap(test)
res = cowplot::plot_grid(mfs$gtable, mfs_ma$gtable, mfs_fe$gtable,
ncol= 3, labels=LETTERS[1:3])
ggsave(res, file="test.pdf", units = "mm", width=180, height=90)
参考:
how to merge images into one file in a defined order
R | ggplot2拼图 —— patchwork
cowplot乃旧爱,patchwork是新欢
【r<-ggplot2】cowplot介绍
【画图】pheatmap多图组合
ggsave: Save a ggplot