r - 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_A
vs smp1_B
,smp2_A
vs smp2_B
... = 4 个图
我想要一个有 2 页的 PDF,在第一页plot1
和plot2
第二页plot3
et 和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 倍于相同的图。
我不明白我的错误在哪里。
解决方案
我会建议两种方法。您可以以日志格式重塑数据并使用构面,或者您可以拆分重塑的数据并使用函数以所需的顺序创建图。这是两个选项的代码。第一种选择是使用方面:
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 中。
推荐阅读
- aws-lambda - AWS Lambda 函数中的 CDI 注入对象为空
- javascript - 选择的发布值始终为 -1 / 无法获取先前选择的值
- javascript - 如何从我的 javascript 组件中触发一个函数,该函数可能存在于导入它的文件中,也可能不存在?
- flutter - Dart/Flutter WebSocket 服务器/客户端在同一侧无法正常工作
- bash - 第二个参数是获取shell脚本函数中第一个参数的内容
- xcode - 如何更改 Flutter.podspec 文件中的 s.ios.deployment_target = '8.0'?
- css - 如何使flex父中的文本不填充宽度
- python-3.x - 创建循环以运行脚本 n 次并将输出添加到新数据帧
- regex - 可以将权重应用于每个元素是模式匹配算法吗?
- testing - Jest-Puppeteer 在一个文件中测试多个案例