【发布时间】:2018-11-13 08:43:25
【问题描述】:
我正在使用 forloop 生成几个热图,并且在每次迭代中我想使用 dev.copy2pdf 生成一个 pdf。当我放弃 for 循环并只复制和粘贴每个迭代之后,代码就可以正常工作(每个热图大约 600kb。但是如果我使用 for 循环,我会得到空的 pdf。
我认为这是因为 for 循环没有给 dev.copy2pdf 足够的时间来生成图表。或者可能是因为其他原因......
有什么办法可以解决这个问题?
这是我的代码:
# specify where you want to deposit the pdf of the graphs
graphpath =
attmeasures = c('c','d')
for (inv in c('a','b')) {
for (m in 1:length(attmeasures)) {
plot.new()
x11()
xvar<- seq(1,36,1)
yvar<- seq(1,12000,1)
intensityvar<-expand.grid(yrmth=xvar, cid=yvar)
intensityvar$intvar = sample(1:100,length(xvar)*length(yvar),replace=T)
graphtitle = paste0('heatmap', attmeasures[m], inv, sep='')
intensityvar_heat<- ggplot(intensityvar, aes(yrmth, cid, z= intvar)) +
geom_tile(aes(fill = intvar)) + theme_bw() +
scale_fill_gradient2(low="yellow", mid="seagreen3", high="blue4",
midpoint = 50,
guide="colourbar",na.value="white", name = paste("monthly ", attmeasures[m], sep=''))
intensityvar_heat + labs(x='date', y='id') +
theme(plot.caption=element_text(size=8, hjust=0, margin=margin(t=15)))
dev.copy2pdf(file = paste(graphpath, graphtitle, ' ',
".pdf", sep=''), paper="a4r", width=10, height=10)
dev.off()
}
}
【问题讨论】:
-
如果您在同一个循环结构中替换一个小图,您的代码是否有效?
-
你能分享你的代码吗?也许你忘了在 for 循环结束之前运行
dev.off()? -
@Esther 它适用于较小的图表; @chinsoon12 我试过
dev.off()也不管用;我已经编辑了帖子以包含我的代码 -
@Amazonian 感谢您的代码。如果您直接调用
pdf而不是dev.copy2pdf,会发生什么?