箱线图合并散点图拼图

展示两组数据之间的相关性散点图和差异箱线图

目录

数据格式

绘图

相关性散点图

箱线图

合并


数据格式

整理R自带鸢尾花数据进行测试

rm(list = ls()) 
library(ggplot2)
library(ggpubr)
library(cowplot)
data <- iris##鸢尾花数据集
data1 <- data[,c(1,2,5)]
data2 <- data1[data1$Species=="setosa"|data1$Species=="versicolor",]

##数据查看
dim(data2)
[1] 100   3
table(data2$Species)#剩下2种
setosa versicolor  virginica 
50         50          0 

箱线图合并散点图拼图_第1张图片

绘图

相关性散点图
pdf("plot.pdf",width = 8,height = 6)##一定添加大小
# 相关性散点图
p1 <- ggscatter(data2, 
                x = "Sepal.Length", y = "Sepal.Width",
                color = "Species",
                palette = c(setosa = "#3C6FAC",versicolor = "grey60"),
                add = "reg.line",  
                add.params = list(color = "red", fill = "grey50"), 
                conf.int = TRUE) + 
  stat_cor(method = "pearson", 
           label.x = min(na.omit(data2$Sepal.Length)), 
           label.y = max(na.omit(data2$Sepal.Width))) +
  theme_bw() + 
  ylab("Sepal.Width") +
  xlab("Sepal.Length") + 
  theme(axis.text.x = element_text(hjust = 0.5, size = 10, color = "black"),
        axis.text.y = element_text(size = 10, color = "black"),
        axis.ticks = element_line(size=0.2, color="black"),
        axis.ticks.length = unit(0.2, "cm"),
        legend.position = "none",
        panel.background = element_blank(),
        axis.title = element_text(size = 10),
        axis.text = element_text(size = 10))
箱线图
# 箱型图(不同类型的Sepal.Width差异)
p2 <- ggplot(na.omit(data2), 
             aes(x = Species, y = Sepal.Width, fill = Species)) + 
  geom_boxplot(aes(col = Species)) + 
  scale_fill_manual(values = alpha(c("#3C6FAC","grey50"),0.8)) + 
  scale_color_manual(values = c("#3C6FAC","grey50")) + 
  xlab("Species") + ##X轴名称
  ylab("") + 
  theme_bw() +
  #主题设置 
  theme(legend.position = "top",#添加图例
        #legend.title = "Species",
        legend.key.size = unit(0.5, "cm"),#缩小图例大小
        axis.text.x = element_blank(),
        axis.text.y = element_blank(),
        axis.ticks = element_blank(),
        panel.border = element_blank(),
        panel.grid = element_blank(),
        panel.background = element_blank(),
        axis.title = element_text(size = 10),
        axis.text = element_text(size = 10)) + 
  stat_compare_means(method = "wilcox.test", 
                     label = "p.signif", 
                     label.y = max(na.omit(data2$Sepal.Width)) * 0.95, 
                     label.x = 1.5, size = 8)
合并
# 合并图像
plot_grid(p1, p2,
          labels = c("","",""), # 无图例
          rel_widths = c(0.7,0.3), # 左边散点图大一些,右边小一些
          axis = "tblr", # 四周对齐
          align = 'h', # 水平摆放
          ncol = 2, # 两列
          scale = c(1,1), greedy = T)
dev.off()

箱线图合并散点图拼图_第2张图片

箱线图详细可学习

跟着 Cell 学作图 | 3.箱线图+散点+差异显著性检验-CSDN博客

你可能感兴趣的:(r语言)