R plotggplot2

R语言 ggplot2 多图排列 Part(1)

2021-02-08  本文已影响0人  Jason数据分析生信教室

在写论文或者报告的时候,肯定会不可避免的遇到编辑多图成一个图的情况。其实方法可以有很多,比方说最笨的办法用PPT自己手动拖移,再高级一点的用PS软件。但是都很繁琐(笔者惭愧的表示这些方法都用过)。仔细想想,好不容易用ggplot2画出了至少看上去高上大的图,到头来还是要靠PPT排版,是不是心里会有些不甘心呢。如果和我一样选择是的小伙伴,那请继续往下看文章,肯定可以给你带来不一样的体验。
本文使用到的包有gridExtra cowplotggpubr
通过阅读本文你可以学会以下技能,把所组不一样的图,表,文字融合到一个页面中间。

1. 合并多图

1.1 制作独立的图

在此也是便于重复,使用程序自带的数据ToothGrowthmtcars

data("ToothGrowth")
head(ToothGrowth)
data("mtcars")
mtcars$name <- rownames(mtcars)
mtcars$cyl <- as.factor(mtcars$cyl)

画箱图,蜂巢图,棒状图,点图

bxp <- ggboxplot(ToothGrowth, x = "dose", y = "len",
                 color = "dose", palette = "jco")
bxp
dp <- ggdotplot(ToothGrowth, x = "dose", y = "len",
                color = "dose", palette = "jco", binwidth = 1)
dp
bp <- ggbarplot(mtcars, x = "name", y = "mpg",
                fill = "cyl",               # change fill color by cyl
                color = "white",            # Set bar border colors to white
                palette = "jco",            # jco journal color palett. see ?ggpar
                sort.val = "asc",           # Sort the value in ascending order
                sort.by.groups = TRUE,      # Sort inside each group
                x.text.angle = 90           # Rotate vertically x axis texts
)
bp + font("x.text", size = 8)
sp <- ggscatter(mtcars, x = "wt", y = "mpg",
                add = "reg.line",               # Add regression line
                conf.int = TRUE,                # Add confidence interval
                color = "cyl", palette = "jco", # Color by groups "cyl"
                shape = "cyl"                   # Change point shape by groups "cyl"
)+
  stat_cor(aes(color = cyl), label.x = 3)       # Add correlation coefficient
sp

最后用ggarrange()来整合这四张独立的图

ggarrange(bxp, dp, bp, sp + rremove("x.text"), 
          labels = c("A", "B", "C","D"),
          ncol = 2, nrow = 2)

用的缩小图,导致最后一张图的注释都凑到一起去了,原图没有问题,在此可以不用在意。

还可以添加文字对图进行注释

figure <- ggarrange(sp, bp + font("x.text", size = 10),
                    ncol = 1, nrow = 2)
annotate_figure(figure,
                top = text_grob("Visualizing mpg", color = "red", face = "bold", size = 14),
                bottom = text_grob("Data source: \n mtcars data set", color = "blue",
                                   hjust = 1, x = 1, face = "italic", size = 10),
                left = text_grob("use ggpubr", color = "green", rot = 90),
                right = ":-)!:-)!:-)!:-)!:-)!",
                fig.lab = "Figure 1", fig.lab.face = "bold")

当然还有第二部分,有兴趣的同学可以接着看R语言 ggplot2 多图排列 Part(2)

上一篇下一篇

猜你喜欢

热点阅读