159

を使用して複数のプロットをプロットし、 を使用しggplot2て配置しようとしていgrid.arrange()ます。私が抱えている正確な問題を説明している人を見つけることができたので、リンクの問題の説明から引用しました:

ggsave()afterを使用する場合grid.arrange()、つまり

grid.arrange(sgcir1,sgcir2,sgcir3,ncol=2,nrow=2)
ggsave("sgcirNIR.jpg")

グリッド プロットは保存しませんが、最後の個々の ggplot を保存します。または同様のものgrid.arrange()を使用し て表示されたプロットを実際に保存する方法はありますか? ggsave()古い方法を使用する以外

jpeg("sgcirNIR.jpg")
grid.arrange(sgcir1,sgcir2,sgcir3,ncol=2,nrow=2)
dev.off()

同じリンクは以下の解決策を提供します:

require(grid)
require(gridExtra)
p <- arrangeGrob(qplot(1,1), textGrob("test"))
grid.draw(p) # interactive device
ggsave("saving.pdf", p) # need to specify what to save explicitly

ただし、 linkから取得した次のコードでggsave()、呼び出しの出力を保存する方法がわかりません。grid.arrange()

library(ggplot2)
library(gridExtra)
dsamp <- diamonds[sample(nrow(diamonds), 1000), ] 

p1 <- qplot(carat, price, data=dsamp, colour=clarity)
p2 <- qplot(carat, price, data=dsamp, colour=clarity, geom="path")

g_legend<-function(a.gplot){
tmp <- ggplot_gtable(ggplot_build(a.gplot))
leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
legend <- tmp$grobs[[leg]]
return(legend)}

legend <- g_legend(p1)
lwidth <- sum(legend$width)

## using grid.arrange for convenience
## could also manually push viewports
grid.arrange(arrangeGrob(p1 + theme(legend.position="none"),
                                        p2 + theme(legend.position="none"),
                                        main ="this is a title",
                                        left = "This is my global Y-axis title"), legend, 
                     widths=unit.c(unit(1, "npc") - lwidth, lwidth), nrow=1)

# What code to put here to save output of grid.arrange()?
4

7 に答える 7

154

grid.arrangeデバイスに直接描画します。arrangeGrob一方、 は何も描画しませんが、 にg渡すことができる grob を返しますggsave(file="whatever.pdf", g)

指定されていない場合、デフォルトで最後のプロットが保存される ggplot オブジェクトとは異なる動作をする理由は、ggplot2 が最新のプロットを目に見えないように追跡grid.arrangeするためです。

于 2013-06-12T21:07:30.860 に答える
59

babptiste の提案にはいくつか問題がありましたが、ようやく入手できました。使用するものは次のとおりです。

 # draw your plots
 plot1 <- ggplot(...) # this specifies your first plot
 plot2 <- ggplot(...) # this specifies your second plot
 plot3 <- ggplot(...) # this specifies your third plot

 #merge all three plots within one grid (and visualize this)
 grid.arrange(plot1, plot2, plot3, nrow=3) #arranges plots within grid

 #save
 g <- arrangeGrob(plot1, plot2, plot3, nrow=3) #generates g
 ggsave(file="whatever.pdf", g) #saves g

これはうまくいくはずです。

于 2015-01-25T12:03:33.813 に答える
27

grid.arrange を pdf ファイルに保存するもう 1 つの簡単な方法は、pdf() を使用することです。

pdf("filename.pdf", width = 8, height = 12) # Open a new pdf file
grid.arrange(plot1, plot2, plot3, nrow=3) # Write the grid.arrange in the file
dev.off() # Close the file

テーブルなど、ggplots 以外のものを配置にマージすることができます...

于 2015-08-18T07:08:36.397 に答える