首页 > 解决方案 > 使用 ggplot2 或 ggpubr 的不同个体及其散点图之间的相关性

问题描述

我的样本代表是:

dat<-read.table(text=" AN1	AN2	AN3	ANM1	ANM2	ANM3
82	78	77	98	86	93
79	73	99	85	86	77
82	74	84	79	73	76
89	73	96	83	72	80
70	71	72	84	76	99
78	76	95	87	76	98
72	87	74	76	79	88
95	85	85	96	94	81
72	86	99	76	93	72
80	97	90	95	77	91
94	95	79	90	78	95
94	83	84	91	73	100
77	92	95	82	83	95
82	82	84	78	96	90
81	83	85	71	76	95
89	79	87	72	99	98
93	96	84	74	82	86
77	98	89	84	87	86
86	98	92	95	72	89
98	92	99	87	93	99",header=TRUE)

我想在 AN1 和 ANM1 之间建立关联;AN2 和 ANM2 以及 AN3 和 ANM3 使用一个循环。我想获得此处提供的“基本情节” 。所以我会分别得到三个散点图。

我使用了以下代码,但它不起作用:

AN<-  dat[1:3]; ANM<- dat[4:6];
lapply(1:3, function(x) ggscatter(AN=[,x],ANM[,x]))

标签: rggplot2scatter-plotggpubr

解决方案


我认为使用for循环您的代码会更好看。所以,为了纯粹地重现你的例子,我会做这样的事情:

library(ggpubr)

dat<-read.table(text=" AN1  AN2 AN3 ANM1    ANM2    ANM3
82  78  77  98  86  93
79  73  99  85  86  77
82  74  84  79  73  76
89  73  96  83  72  80
70  71  72  84  76  99
78  76  95  87  76  98
72  87  74  76  79  88
95  85  85  96  94  81
72  86  99  76  93  72
80  97  90  95  77  91
94  95  79  90  78  95
94  83  84  91  73  100
77  92  95  82  83  95
82  82  84  78  96  90
81  83  85  71  76  95
89  79  87  72  99  98
93  96  84  74  82  86
77  98  89  84  87  86
86  98  92  95  72  89
98  92  99  87  93  99",header=TRUE)

for(i in 1:3){ 
  AN <- paste0("AN", i)
  ANM <- paste0("ANM", i)
  print(
        ggscatter(dat, x = AN, y = ANM)
      )

} 

为了尝试从提供的链接中创建与基本图类似的东西,我会将for循环更改为:

for(i in 1:3){ 
  AN <- paste0("AN", i)
  ANM <- paste0("ANM", i)
  print(
      ggscatter(dat, x = AN, y = ANM, 
                  add = "reg.line", 
                  conf.int = TRUE, 
                  add.params = list(color = "blue", fill = "lightgray")) + 
      stat_cor(method = "pearson", label.x = 3, label.y = 30) # Here label.x and label.y deform the plot, seems to be a case to tune them to your needs.
      )

}

现在,如果你必须使用lapply我会尝试通过创建一个函数来创建一些抽象:

create_plot <- function(data, prefix_x, prefix_y, index) { 

  x_col <- paste0(prefix_x, index)
  y_col <- paste0(prefix_y, index)

  g <- ggscatter(data, x = x_col, y = y_col, 
                 add = "reg.line", 
                 conf.int = TRUE, 
                 add.params = list(color = "blue", fill = "lightgray")) + 
    stat_cor(method = "pearson")

  return(g)

}

lapply(1:3, create_plot, data = dat, prefix_x = "AN", prefix_y = "ANM")

推荐阅读