使用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使用循环。我想获得here可用的“基本图解”。所以我将分别获得三个散点图。

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

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

sonnysong 回答:使用ggplot2或ggpubr

我认为使用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)
  print(
      ggscatter(dat,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,fill = "lightgray")) + 
    stat_cor(method = "pearson")

  return(g)

}

lapply(1:3,create_plot,data = dat,prefix_x = "AN",prefix_y = "ANM")
本文链接:https://www.f2er.com/2960161.html

大家都在问