R + ggplot:绘制多个页面 [英] R + ggplot: plotting over multiple pages

查看:103
本文介绍了R + ggplot:绘制多个页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个函数,在多个页面上绘制ggplot facet_wrap 图。这只是一个黑客,因为这个功能似乎在ggplot2功能待办事项列表中。我做了一些小计算,以找到我需要的页数,我每页需要的 data.frame 的行数等等。相当有信心这一切工作。

  pdf(文件名)
(i seq(num_pages)){
slice = seq( ((i-1)* num_rows)+1,(i * num_rows))
slice = slice [!(slice> nrow(df.merged))]
df.segment = df.merged [片段]
p <-ggplot(df.segment,aes(y =平均值,x =表型))
p <-p + geom_bar(stat =identity,fill =white ,color =black)
p + facet_wrap(ID,scales =free_y,ncol = n_facets,nrow = n_facets)
}
dev.off()

我的问题是,通过将它全部包装在这样的for循环中,在 pdf() dev.off()函数,是for循环似乎并没有等待ggplot去做它的事情,并迅速通过其循环并输出无效的PDF。



如果我设置 i = 1 ,请启动 pdf(),在for循环中运行上面的代码,然后设置 i = 2 ,然后运行代码,依此类推直到我感到无聊( i = 3 ),然后关闭设备,生成的PDF文件非常棒。



有没有一种方法可以让for循环等待最后一行完成绘图,然后再进入下一次迭代?
<解决方案我认为问题在于你需要在最后一行(p + ...)中使用print()来实际打印到for循环中的设备。 。 。

I'm trying to write a function that plots a ggplot facet_wrap plot over multiple pages. It's just a hack, as this feature seems to be on the ggplot2 feature to-do list. I do some small calculations to find the number of pages I'm going to need, the number of rows of my data.frame that I need per page etc. I'm pretty confident this all works.

pdf(filename)
for (i in seq(num_pages)){
    slice = seq(((i-1)*num_rows)+1,(i*num_rows))
    slice = slice[!(slice > nrow(df.merged))]
    df.segment=df.merged[slice,]
    p <- ggplot(df.segment, aes(y=mean,x=phenotype))
    p <- p + geom_bar(stat="identity",fill="white",colour="black") 
    p + facet_wrap("ID",scales="free_y",ncol=n_facets,nrow=n_facets)
}
dev.off()

My problem is that, by wrapping it all up in a for loop like this, in between the pdf() and dev.off() functions, is that the for loop doesn't seem to wait for ggplot to do its thing, and blazes through its loop very quickly and outputs an invalid PDF.

If I set i = 1, start the pdf(), run the above code inside the for loop, then set i=2, then run the code, and so on until I get bored (i=3) then turn off the device the resulting PDF is brilliant.

Is there a way I can get the for loop to wait for the final line to finish plotting before moving onto the next iteration?

解决方案

I think the problem is that you need print() around your last line (p+ ...) to get it to actually print to the device inside the for loop . . .

这篇关于R + ggplot:绘制多个页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆