首页 > 解决方案 > 4个不同的情节成为一个独特的情节

问题描述

我使用这个示例数据集:

gene smp1_A smp1_B smp2_A smp2_B smp3_A smp3_B smp4_A smp4_B
geneA 10 12 30 33 26 22 44 42
geneB 15 13 11 16 15 16 21 26

我想绘制smp1_Avs smp1_Bsmp2_Avs smp2_B... = 4 个图
我想要一个有 2 页的 PDF,在第一页plot1plot2第二页plot3et 和plot4.
(当然,我的真实数据集中有更多的图)。

library(ggplot2)
library(ggpubr)

data = read.table('test_data.txt',header=T)
samples = list('smp1','smp2','smp3','smp4')

for (i in 1:length(samples)){ 

    smp = samples[i]
    smpA = paste(smp,"A",sep="_")
    smpB = paste(smp,"B",sep="_")
        
    plot = ggplot(data, aes(x=data[,smpA], y=data[,smpB])) + geom_point()

    # I can't add the plot to a PDF in a loop, I have to generate it at the end
    # so I need to create a new variable each iteration to not overwrite the previous one 
    # I do it with assign

    nam <- paste("plot", i, sep = "")
    assign(nam, plot)
}

# at this point, if I try to plot my 4 plots separately, it's working fine.
# I have this 4 variables in my env : plot1, plot2, plot3, plot4 

# But now when I try to create my PDF I get 4 times the same plot and I can't figure out which one is it. 
page1 = ggarrange(plot1,plot2, ncol=2, nrow=1)
page2 = ggarrange(plot3,plot4, ncol=2, nrow=1)
plots = list(page1, page2)
pdf('test_plots.pdf')
plots
dev.off()

就像我在代码中所说的那样,当我单独打印我的图时它正在工作,但是当我将它们组合成 PDF 时,我有 4 倍于相同的图。
我不明白我的错误在哪里。

标签: rggplot2ggpubr

解决方案


我会建议两种方法。您可以以日志格式重塑数据并使用构面,或者您可以拆分重塑的数据并使用函数以所需的顺序创建图。这是两个选项的代码。第一种选择是使用方面:

library(tidyverse)
#Code option 1
#Reshape data
df %>% pivot_longer(-gene) %>%
  #Separate sample type
  separate(name,into=c('sample','type'),sep = '_') %>%
  ggplot(aes(x=type,y=value,color=gene))+
  geom_point()+
  facet_wrap(.~sample,scales = 'free')+
  theme_bw()+
  ggsave(filename = 'Myplot.pdf',width = 35,height = 18,units = 'cm')

输出将是这个并保存在 pdf 中Myplot.pdf

在此处输入图像描述

第二个选项是处理数据并根据每张幻灯片中所需的绘图数量创建一个键。这里的代码:

#Code option 2
#Process data
dfp <- df %>% pivot_longer(-gene) %>%
  #Separate sample type
  separate(name,into=c('sample','type'),sep = '_')
#Keys
dfk <- data.frame(sample=unique(dfp$sample))
dfk$Key <- rep(1:2,each=2)
#Match
dfp <- dfp %>% left_join(dfk)
#Create list
List <- split(dfp,dfp$Key)
#Function for plot
myplot <- function(x)
{
  #Plot
  G <- ggplot(x,aes(x=type,y=value,color=gene))+
    geom_point()+
    facet_wrap(.~sample,scales = 'free')+
    theme_bw()
  return(G)
}
#Apply
List2 <- lapply(List,myplot)

最终pdf中的幻灯片可以通过以下方式获得:

#Export
pdf('Myexample.pdf',width = 14)
for(i in 1:length(List2))
{
  plot(List2[[i]])
}
dev.off()

它看起来像这样:

在此处输入图像描述

在此处输入图像描述

它将出现在两张幻灯片 pdf 中。


推荐阅读